well my question is theory based that why aren't constructor and destructors inherited from the base class. As far as i know they fall under the category of member functions and in public inheritance all the functions are inherited apart from them. Why?
They aren't inherited, but they are called. The base class constructor is called to construct the base object before the derived class constructor is called. When the object is destroyed, it's the reverse: the derived class destructor is called first, then the base class destructor.
By default the base class's default constructor called but the the derived class can control which the base class constructors is called, and what parameters are passed to it.
How could you call the ctor/dtor unless it was inherited?
I always considered ctors and dtors to be inherited because they are passed down the hierarchy, are callable, and have protected/public/private accessibility just like any other member.
The only thing that sets them apart is that they are automatically called.
they are automatically called but are they inherited aswell from the base class just like other functions or not? Please give me a reason too once saying yes or no. im confused with varying answers.
they are automatically called but are they inherited aswell from the base class just like other functions or not?
I guess it depends on your definition of "inherited"
I'm saying yes because to me, if a child inherits something, it means it has it (or at least has access to it). And child classes certainly do have access to their parents ctors and dtors -- therefore they clearly have inherited them.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Parent
{
public:
void func() {} // normal member
~Parent() {} // dtor
};
class Child : public Parent // Child derives from Parent
{
public:
void func2()
{
Parent::func(); // call inherited 'func' function
Parent::~Parent(); // call inherited Parent dtor
}
};
So yeah -- a child has access to parent ctors/dtors, and therefore it must have inherited them (how else could it have access to them?).
But again note that even though you can call dtors like this, you absolutely shouldn't.
class Parent
{
public:
void func() {} // normal member
~Parent() {} // dtor
};
class Child : public Parent // Child derives from Parent
{
public:
void func2()
{
Parent::func(); // call inherited 'func' function
Parent::~Parent(); // call inherited Parent dtor //error in this line
}
};
the compiler says that " no matching function for call to 'Child::~Child() "
Maybe I'm wrong and it's just VS allowing me to do things I shouldn't be able to do. I wonder what the standard says on the subject -- which compiler is doing it right?