I am new in C++ and I have just started studying polymorphism. I know that if I create an object for the derived class then the constructor of both derived and base class is get called. Does it mean that, when I create an object for the derived class, eventually I am ending up with two objects- one is created by the constructor of base class and another one created by the constructor of derived class?
Can anyone explain, what is the job of base class constructor when I want to create an object for the derived class.
The job of the base class constructor is to initialise the base class member variables (consider the case of a private member variable in the base class).
When you call a constructor for a derived object, you only end up with one object. The base class constructor initialises the base class parts of the new object, and the derived constructor initialises the derived class parts of the same new object.
Constructors do not allocate space and initiate instances of objects; they initialise the object immediately after space has been allocated.
When you declare a object on the stack or use new first the memory is reserved and object is created, then the constructors are executed, starting with the base constructor and working upwards towards the most derived class.
You will end up with a derived class object, that contains a base class object.
Constructors don't magically create another instance of an object. They initialise a certain piece of memory, but calling a constructor and allocating memory are not the same thing -- the latter is either done behind the scenes (for objects with automatic and static storage duration) or with new and malloc (for objects with dynamic storage duration).
EDIT: Before I get angry comments about it: "behind the scenes" is a vague way to put it; the definition of an object with automatic or static storage duration ensures that it gets memory.
Whether you are creating an object of the base class or derived class, you end up with one object.
Just because the base class constructor is called, it doesn't mean you get one extra object for that call. Here, the base class constructor will be executed, which typically sets attributes of the base class. The object on the whole would be composed of the base class properties and derived class properties.
If you have a class then you would have to define a contructor or constructors (there are certain circumstances in where you do not have to). A constructor has the purpose to initialise the class data members, you give a value to its data members. Any data member that you do not give it a value, will have an undefined value unless the data member is an instance of a class that happens to have a default constructor.
So when you create an instance of that class, the compiler will invoke the appropriate constructor, and the members of the instance that you have just created will have data initialised with values as you set them in the constructor.
If you have a derived class, you can add data members to it, but remember that it has also an inherited member: the base class. So when you define a constructor in you derived class, you must invoke a constructor of the base class (so that the members of the base class get fully initialised) and assign value to the derived class own data members.
So you create an instance of the derived class, the derived class constructor is invoved. As part of its functionality it invokes the constructor of its base class (so you might say two constructors but this is the wrong of viewing it).
If you create an instance of the base class, only that constructor is invoked.
When we create an object, Constructor will be called. Its not when constructor called object is being created.
You can assume Creating object as a function and Constructor is another function which is called inside it.
Assume A is a base class and B is a derived class,
class A
{
}
class B : public A
{
}
We will be creating object for class A in below ways,
A obja;
or
A obja = new A();
In both cases you can assume a function Create is getting called,
A::Create()
{
A();
}
If you are creating Derived class B object then Create method of B will be called,
So internally Create method of B will look like below,
B::Create()
{
B();
A();
}
So when we create Derived class object first derived class initialization happens and then Base class initialization happen. It not means object is created twice.
Object will be created for the Call where you are creating object using.
B obj;
or
B obj = new B();
Calling the constructors are internal functionality as Constructors called in the Create function.
Note : Create function in the above code is done only for illustrative purpose.
when object of a derived class is created then constructor function of that class will be created first then to use the constructor function of the base class will be called by a separate object at the time of calling it will be invoked by that object.
Related
Consider the below simple program of inheritance
#include <iostream>
class A
{
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C x;
}
Now my question is
How many objects are created ? One or three?
Also, in case one object, does it mean it creates a layered object ?
What I wanted to ask was ,when we call constructor of base classes , what is happening as we have only one object (from the object perspective) ? What all things C object x will have ,and what all things are deleted when destructors of base class is called?
How is memory allocated for C's object?
Just to make everyone know ,I do understand
When we are creating an object of the derived class, we end up with one object only .
But the question is ,internally do the derived class object c will wrap the two objects of A and B or , will just public/protected attributes will be copied to the object.
Also is the below line correct?
"When we declare a object on the stack or use new first the memory is reserved and object is created, then the constructors are executed, starting with the base constructor and working upwards towards the most derived class ?"
Only one object of type class C would be created.
So basically in this case, constructors of base classes are called first before the constructor of the derived class is called. In the end, the object of derived class also contains the contents of bases classes.
One object is created, of type C, which contains all of the members of A, B, and C.
Here are some additional information about the relation between a base-class object and a derived-class object:
Every derived object contains a base-class part to which a pointer or reference of the base-class type can be bound. That's the reason why a conversion from derived to base exists, and no implicit Conversion from base to derived.
A base-class object can exist either as an independent object or as part of a derived object.
When we initialize or assign an object of a base type from an object of a derived type, only the base-class part of the derived object is copied, moved, or assigned. The derived part of the object is ignored.
see "C++ Primer Fifth Edition" ยง15.2.3
I know that when assign the derived object to base object, the slicing happens. The first part of derived class object will copied to the base object.
And here is my quesition:
Will the vptr(virtual table pointer) be copied to base class object?
If vptr is not copied to base class object(I guess, for the object assignment will not cause polymorphism), why? Is there any rule to support that?
No, no vtable pointer is copied. Nor could it be, since the destination object is truly of base class type both before and after the assignment.
Virtual methods called on a sliced object will invoke the base class implementations.
I have written a pure virtual destructor and implemented it in the abstract base class and override it in derived classes.
However, in one of the classes I have a pointer to a base class object.
Now, should the destructor of the derived class be written this way:
virtual ~DerivedClass()
{
delete this->pointerToAnotherDerivedClassObject;
}
or will the object be deleted automatically? As the base class destructor is always called so I cannot decide whether it takes care of it or not.
EDIT: My mistake for stating it was a pointer to a base class, as it is actually a pointer for another derived class object.
However, in one of the classes I have a pointer to a base class object.
Now, should the destructor of the derived class be written this way
Since pointerToAnotherDerivedClassObject points at another object in memory, then yes, your DerivedClass destructor needs to explicitly delete that object (or wrap the raw pointer inside a smart pointer - std::auto_ptr, std::unique_ptr, or std::shared_ptr - and let it delete the object for you) ONLY IF DerivedClass is meant to own that other object. Otherwise, do not delete it if you do not own it.
#Elia Similar situation is discussed in the book of Eckel " thinking in C++ vol-2 " in design pattern chapter-10 regarding pseudo virtual constructor. The answer to your question is you do need to delete it considering you allocate it dynamically. Also don't confuse member Base* with the Base object which is part of derived due to inheritance, one is a data member (which is what you want to delete) other is due to inheritance.
Someone told me that constructor creates the objects. But on internet I searched that constructor executed when objects created.. Can you explain about this? I'm new to C++
In C++ a constructor is a special kind of class member function that
is executed when an object of that class is instantiated.
Constructors are typically used to initialize member variables of the
class to appropriate default values, or to allow the user to easily
initialize those member variables to whatever values are desired.
So when you call the constructor you have an already instantiated object, so the constructor doesn't create the object, nor creates the objects variables, it is simply used to initialize the variables inside that object (or to make some task you want to before the object is used).
EDIT: Also:
A constructor performs its work in this order:
It calls base class and member constructors in the order of
declaration.
If the class is derived from virtual base classes, it
initializes the object's virtual base pointers.
If the class has or
inherits virtual functions, it initializes the object's virtual
function pointers. Virtual function pointers point to the class's
virtual function table to enable correct binding of virtual function
calls to code.
It executes any code in its function body.
Check these links for more infos:
http://www.learncpp.com/cpp-tutorial/85-constructors/
https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx
https://isocpp.org/wiki/faq/ctors
class a{int a = 0;int b = 0;} a obj = new a();
in above code
your obj is created memory for obj is allocated in stack and then constructor
code is execute
I have a class called MyBase which has a constructor and destructor:
class MyBase
{
public:
MyBase(void);
~MyBase(void);
};
and I have a class called Banana, that extends MyBase like so:
class Banana:public MyBase
{
public:
Banana(void);
~Banana(void);
};
Does the implementation of the new constructor and destructor in Banana override the MyBase ones, or do they still exist, and get called say before or after the Banana constructor / destructor executes?
Thanks, and my apologies if my question seems silly.
A Base constructor will always be called before the derived constructor.
The Base destructor will be called after Dervided destructor.
You can specify on derived constructor which Base constructor you want, if not the default one will be executed.
If you define other constructors but not default and don't specify on Derived constructor which one to execute it'll try default which doesn't exist and will crash compilation.
The above happens because once you declare one constructor no default constructors are generated.
Constructors cannot be overriden. You can't declare a base class constructor in a derived class. A class constructor has to call a constructor in base class (if one is not explicitly stated, the default constructor is called) prior to anything else.
To be able to clean up the derived class correctly, you should declare the base class destructor as virtual:
virtual ~MyBase() { ... }
It should say
class Banana : public MyBase
{
public:
Banana(void);
~Banana(void);
};
The constructor of the derived class gets called after the constructor of the base class. The destructors get called in reversed order.
The constructors are called top down in the inheritance tree. This is so that the derived constructor can count on the base object being fully initialized before it tries to use any properties of the base.
Destructors are called in reverse order of the constructors, for the same reason - the derived classes depend on the base, but the base doesn't depend on the derived.
If there is any possibility of destroying the object through a pointer to a base class, you must declare all of the destructors virtual.
Constructors and destructors are special member functions. In general you will read everywhere that construction starts from the least derived type all the way in the hierarchy down to the most derived type. This is actually the order in which constructor execution completes, but not how construction is started.
Constructors initialization list execution order guarantees that while the most derived object's constructor will be the first constructor to start executing it will be the last constructor to complete
When you instantiate an object the most derived constructor that matches the construction call gets called first. The initialization list of the matched most derived constructor starts, and initialization lists have a fixed order: first the constructors of the base classes in order or appearance within the inheritance list get called. Then the member attribute constructors are called in the order in which they appear in the class declaration (not the order in which they appear in the initialization list). After the whole initialization list (at each level) completes, the constructor body block is executed, after which the constructor call completes.
All base destructors will be called in reverse order of construction after the most derived destructor has completed execution. Destruction happens in exact reverse order of construction.
Destructors are special in a different way: they cannot be overriden. When you call the most derived destructor of a class, it will complete the execution of the destructor body, after which all member attribute destructors will be called in reverse order of creation. After the most derived destructor has completed and so have done the member destructors of the most derived object, the destructor of its most direct bases start in reverse order of construction, the destructor bodies will execute, then the member attributes destructors and so on... At the end all constructed elements will be destroyed.
Destructors for polymorphic classes should be virtual
The destruction description above starts with the call to the most derived destructor. This can be achieved by calling delete on a pointer to the most derived type, when an auto object goes out of scope or when the object is deleted through a base class whose destructor is virtual.
If you forget to add the destructor keyword in the base class and you try to delete a derived object through a pointer to the base you will call the base destructor directly, and that implies that all sub objects below the pointer type in the hierarchy will not be properly destroyed. All inheritance hierarchies in which you will delete objects through pointers to a base type must have virtual destructors. As a general rule of thumb, if you already have any virtual method, the cost of making the destructor virtual is negligible and is a safe net. Many coding guides enforce that destructors in inheritance hierarchies must be virtual. Some go as far as requesting all destructors to be virtual, This has the intention of avoiding possible resource leaks at the cost of adding a vtable for all types and an vtable pointer for all objects.
You are missing the type of inheritance:
Change
class Banana:MyBase
To:
class Banana: public MyBase
As for
does the implementation of the new
constructor and destructor in Banana
override the MyBase ones, or do they
still exist, and get called say before
or after the Banana constructor /
destructor executes?
The order of inherited executes from bottom to top, that means that MyBase will be called first, then Banana. If you had another subclass, it would be called last.
Take this example:
class RottenBanana : public Banana
The inheritance chain is now RottenBanana -> Banana -> MyBase
The constructors of this class will be called starting at MyBase, then Banana and then calling RottenBanana.
If you instantiate an EEGModeRGB object (which has tri-color led's attached) - then immediately delete it you'd see the colors Blue, Green, Yellow, and Red, for one second each - in that order.
class EEGMode {
public:
EEGMode() { setAllPixelsToColor(BLUE); delay(1000); }
virtual ~EEGMode() { setAllPixelsToColor(RED); delay(1000); }
};
class EEGModeRGB : public EEGMode {
public:
EEGModeRGB() { setAllPixelsToColor(GREEN); delay(1000); }
virtual ~EEGModeRGB() { setAllPixelsToColor(YELLOW); delay(1000); }
};