简体   繁体   中英

converting base class pointer to unknown derived class pointer

I have 5 derived classes from an abstract base class. One function is overloaded which exists in every derived class , let's name it, print() . Example for Derived 4 class:

Derived4::print(*Derived1)
Derived4::print(*Derived2)
Derived4::print(*Derived3)
Derived4::print(*Base)

Like i said before, all derived classes have print function, but arguments are different, like

Derived1::print(*Derived2)
Derived1::print(*Derived3)
Derived1::print(*Derived4)
Derived1::print(*Base)

All objects are stored inside a vector like

vector<Base*> a

When i take one of them from vector and try to call print function, all calls are directed to print(*Base) function.I am not allowed to store the types, therefore don't have any idea what is coming from vector.Also, type checking is not allowed too.

An example:

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    void print(){cout << "greetings from A" << endl;}
};

class C : public A{
public:
    void print(){cout << "greetings from C" << endl;}
};

class D : public A{
public:
    void print(){cout << "greetings from D" << endl;}
}; 

class B : public A{
public:
    void print(C* c){c->print();}
    void print(A* d){d->print();}
};

int main()
{
    D d;
    C c;
    B b;
    vector<A*> a; //B,C,D will be stored inside a vector like this.
    a.push_back(&c);
    a.push_back(&d);
    b.print(a[0]);
    b.print(a[1]);
    return 0;
}

The result:

greetings from A
greetings from A

The desired result:

greetings from C
greetings from A

You need virtual functions. declaring A::print as virtual would make it so that calling print on a pointer of type A will call the print of which class the object was constructed as, instead of using pointer type to decide what print to call.

You also need to remove D::print as you expect A::print get called if the object is of type D

#include <iostream>
#include <vector>
using namespace std;
class A{
public:
    virtual void print(){ cout << "This is printed twice." << endl; }
};

class C : public A{
public:
    void print(){ cout << "This is desired output." << endl; }
};

class D : public A{

};

class B : public A{
public:
    void print(C* c){ c->print(); }
    void print(A* d){ d->print(); }
};

int main()
{
    D d;
    C c;
    B b;
    vector<A*> a; //B,C,D will be stored inside a vector like this.
    a.push_back(&c);
    a.push_back(&d);
    b.print(a[0]);
    b.print(a[1]);
    return 0;
}

The result:

This is desired output.
This is printed twice.

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