Constructors in C++ Concept
Constructors in C++ Concept
&
Destructors in C++
What is constructor?
• A constructor is a member function of a class
which initializes objects of a class. In C++,
Constructor is automatically called when
object(instance of class) is created. It is special
member function of the class.
• To create a constructor, use the same name as
the class, followed by parentheses ().
Example
• class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass Obj; // Create an object of MyClass
//(this will call the constructor)
return 0;
}
Constructor Rules
• The constructor has the same name as the
class and it is always public.
• Constructors can also take parameters (just
like regular functions), which can be useful for
setting initial values for attributes.
• Constructor can not be inherited, but from
the derived class we can call the base class
constructors.
Constructor Rules
• Constructors do not have return type.
• Constructor can not be virtual.
• It is not possible to refers to the address of
constructors.
• It is not possible to use the constructor as
member of union if the object is created with
constructor.
Constructor
• Just like functions, constructors can also be
defined outside the class. First, declare the
constructor inside the class, and then define it
outside of the class by specifying the name of
the class, followed by the scope resolution ::
operator, followed by the name of the
constructor (which is the same as the class):
Example
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};