Pages

Tuesday, November 30, 2010

Constructors / Destructors

Is it possible to have Virtual Constructors?

It is not possible to have virtual constructors. Constructors cannot be virtual because constructor is the code which is responsible for creating instances of a class.

What is a constructor

Constructors creates objects and initializes it. It is also responsible for creating the virtual table for virtual functions. It is different from other methods in the class.

What about a destructor? Can it be virtual?

Destructor can be virtual. At run time, depending upon the caller, it will decided to call the base class or derived class desctructor.

If a derived class object is pointed by a base class pointer, and when you call destructor on it, the derived class destructor will be called, since the destructor is declared virtual in the base class.

If the base class dectructor is not declared virtual, the base class destructor is called, and which is not required by the user.

Hence, Virtual dectructors play an important part in run time polymorphism.



What is the difference between Copy constructor and Assignment operator?

A copy constructor created a new object by using the contents of the argument object, whereas an assignment operator assigns the contents of an existing object to another existing object of the same class.

What is a default constructor ?

A default constructor is a constructor with no arguments values and if has arguments, it would be default values. If the arguments are not default values, then its not a default constructor.


What is a copy constructor ?

Copy constructors are used when u need to create a copy of an object of a class from another object of the same class type. You must use the reference of the class type.
eg

X obj1;
X obj2(obj1);
X obj3 = obj1;

When are copy constructors called?

Copy constructors are called when -

you pass another object as an argument in the constructor of the new object
you pass the object as an argument to a function
a functions returns the object as a value

No comments: