A constructor is a class function with the same name as the class itself. It cannot have a return type and may accept parameters. It is a callback or event for the compiler to call the constructor after memory allocation of the object is complete via new operator. 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 16.
#include<string.h> #include<iostream.h> class std12_student { private: int age; char name[20]; public: std12_student() { 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 = 16 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.
Most popular
Questions index C Questions C++ Questions Win32 MFC COM/DCOM DLL Questions
Compilers & Editors
Download Visual Studio Download XCode Download Visual Studio Code Android studio install sdk Eclipse installer Best C compilers IDEs
Development system setup
Windows media creation tool MSDN subscription Ubuntu virtualbox
New updated posts
Why learn C? Calculate weighted average
Questions index C Questions C++ Questions Win32 MFC COM/DCOM DLL Questions
Compilers & Editors
Download Visual Studio Download XCode Download Visual Studio Code Android studio install sdk Eclipse installer Best C compilers IDEs
Development system setup
Windows media creation tool MSDN subscription Ubuntu virtualbox
New updated posts
Why learn C? Calculate weighted average