简体   繁体   中英

c++ inheritance, constructor real caller

I have class A:

class A
{
    A(const String& name)
    {
        doSomething1();
    }
}

and I have also class B

class B : A
{
    B(const String& name): A(name)
    {
        doSomething2();
    }
}

So if I call B() it will call also A() and it will result with 2x calls doSomething(). Is there any way how to discover in A`s constructor that it is called directly like: A() and when indirectly: B() ?

Thanks

EDIT: Well ok, it is not the same method doSomething() it is more like doSomething1() and doSomething2() but I want call the most outside function so if A has doSomething1() and B doSomething2(), after call B() I want to execute just doSomething2()

In general there's no way to discover from a base class if the object you're referring to is of a derived type.

Anyway your design is most likely flawed, something like this could also work:

#include <iostream>
#include <string>
using namespace std;

class A
{
public:
    A(const string& name)
    {
        doSomethingFromA();
    }

    void doSomethingFromA() {
        cout << "called from A" << endl;
    };
protected:
   A(const string& name, bool fromB)
   {
       doSomethingFromB();
   }

   void doSomethingFromB() {
        cout << "called from B" << endl;
    };
};

class B : public A
{
    public:
    B(const string& name): A(name, true)
    {
    }

};


int main() {

    A obj1("str");

    B obj2("str");

    return 0;
}

http://ideone.com/jj8Df1

by exploiting the visibility of constructors you might pass additional info to the base class. Otherwise I'd advice using a slightly modified CRTP that renders your base class aware of the object itself (they become an entire different entity).

You could have two overloads of doSomething as follow but...

void doSomething(A*);
void doSomething(B*);

And on the call site you do:

doSomething(this);

( this is either A* or B* so it will call the appropriate function.)

class A
{
    A(const String& name)
    {
        doSomething(this);
    }
}

class B : A
{
    B(const String& name): A(name)
    {
        doSomething(this);
    }
}

But , as other said in the comment, you have a design issue!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM