How do we construct a variable in C ? Let us take an example of how we construct a variable in C of type int or char array. Here the variable will be allocated in either the global or local scope and we do a basic initialization. The construction of the class object is very similar. We are specifying the variable type and then the variable name in c language. Here in C++ the syntax and convension are same. We specify the class name and the object name.

    <Veriable Type> <Veriable Name> 
    int i;
    int t = 0;
    char name[10];
    char name[] = "John Smith";
    <Class type> <Object Name>
    student student1;

Constructor function plays crutial role in the construction of the object. A constructor is a member function of class with the same name as the class itself. This cannot have a return type and may accept parameters. The constructor with no argument is also known as default constructor. Constructor with one or more arguments are called overloaded constructors.

C++ class constructor execution flow

It is a callback or event for the compiler. Compiler adds additional code to call the constructor with the self reference (this). This happens once the memory allocation of the object is complete via new operator or the object is allocated in local stack space. Responsibility of constructor function is to set initial values to each object members to some default values before the object can be used.

Example: Here is an example of student class of standard 12. Constructor initializes the default name as blank and age of the student as 18.


class std12_student
  int age;
  char name[20];  
    age = 18;
    strcpy(name, "");
  int get_age()
    return age;
  char* get_name()
    return name;
int main(int argc, char* argv[])
  std12_student s;
  cout << "Age = " << s.get_age();//Default age = 18
  return 0;

About our authors: Team EQA

You have viewed 1 page out of 62. Your C++ learning is 0.00% complete. Login to check your learning progress.