What happens if I throw (pointer to class A) to (pointer to its subclass B) in C ++

A has a static function A :: create (), which creates an instance of A, does some initialization, and returns a pointer to it. I want to create a subclass of A and have a similar create () function:

class B : public A { public: static B* create(); int val; //... } 

in this B :: create () function, I need to do the following:

 B* B::create() { auto b = (B*)A::create(); b -> val = 0; //... return b; } 

Is this right to do? What will happen after the broadcast?

Subsequent actions: A has a protected / closed constructor. How do I write B :: create () or constructor B? I want the vars inherited from A to have the same values ​​as the created A :: create () would have

+6
source share
2 answers

A cast will not do anything reasonable if A::create() does not return a pointer to object B If A::create() returns a pointer to an object that is not B , you have undefined behavior.

In C ++, you are dealing with the initialization of objects using constructors: the initialization of the base classes is inherited, and each derivative can perform any custom initialization that it must perform. Your B::create() will simply return the appropriate object:

 B::B() : A() // initialize base , val(0) { // other initialization } B* B::create() { return new B(); } 
+5
source

You can make class B friend A, like this

 class A { public: static A* createA(); int varA; private: friend class B; // Make B a friend so that B can use private constructor of A A() { cout << "In A constructor" << endl; varA = 5; // Initialize members of A here } }; A* A::createA() { return new A; } class B : public A { public: static B* createB(); int varB; private: B() { cout << "In B constructor" << endl; varB = -5; // Initialize members of B here } }; B* B::createB() { return new B; } int main() { cout << "Create A" << endl; A* x=A::createA(); cout << "x->varA is " << x->varA << endl; cout << endl; cout << "Create B" << endl; B* y=B::createB(); cout << "y->varA is " << y->varA << endl; cout << "y->varB is " << y->varB << endl; cout << endl; delete x; delete y; } 

When a new B is created, constructor A is automatically called and the members of A will be initialized.

Output:

 Create A In A constructor x->varA is 5 Create B In A constructor In B constructor y->varA is 5 y->varB is -5 

Another way is to make the constructor of protected A instead of private.

+2
source

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


All Articles