+ 1
Is constructor and destructor inheritable?
5 ответов
+ 5
The destructor is not inherited, every class has exactly 1 destructor, so it doesn't make sense to inherit one.
The constructor is also not inherited.
However you can delegate it using a using declaration.
class Base
{
public:
Base( int a, int b ){}
};
class Derived : public Base
{
using Base::Base;
};
Derived d( 5, 6 ); // valid now
You can read more here:
https://en.cppreference.com/w/cpp/language/using_declaration
+ 2
~ swim ~ Yea, I was unsure about the terminology there so I just decided to use it anyway hoping someone would correct me, so thx :)
+ 2
ok thank you.
0
Srry, I made a mistake in my answer, I updated it. :)
0
Then what is this how constructor and distructor of base class work on derived class.
#include <iostream>
using namespace std;
class Mother {
public:
Mother()
{
cout <<"Mother ctor"<<endl;
}
~Mother()
{
cout <<"Mother dtor"<<endl;
}
};
class Daughter: public Mother {
public:
Daughter()
{
cout <<"Daughter ctor"<<endl;
}
~Daughter()
{
cout <<"Daughter dtor"<<endl;
}
};
int main() {
Daughter m;
}
/*Outputs
Mother ctor
Daughter ctor
Daughter dtor
Mother dtor
*/