How to create derived classes without having to rewrite the code?

Say I have:

class A { A(int i); }; class B : A { }; 

I cannot set B (3), for example, since this constructor is not defined. Is there a way to create an object B that will use constructor A without having to add “trivial” code in all derived classes? thanks

thanks

+4
source share
3 answers

C ++ 11 has a way:

 class A { public: A(int i); }; class B : A { public: using A::A; // use A constructors }; 
+6
source

If you use C ++ 03, this is the best I can think of in your situation:

 class A { public: A(int x) { ... } }; class B : public A { public: B(int x) : A(x) { ... } } 

You can also check the link below, which is a C # question, but provides a more detailed answer on why constructors can act like this:

C # - Creating all derived classes calls the base class constructor

+2
source

as user491704 said it should be something like this

 class mother { public: mother (int a) {} }; class son : public mother { public: son (int a) : mother (a) { } }; 

Here is the link for the tutorial

+2
source

Source: https://habr.com/ru/post/1379806/


All Articles