Reputation: 93
This my base class
class Base {
protected:
int number;
public:
Base(int num);
virtual void display() = 0;
};
these two classes have inherited Base.
class Derived: public Base {
public:
Derived(int num);
void display(){cout <<"hello";}
void other();
};
class Derived2: public Base {
public:
Derived(int num);
void display(){cout <<"hello other";}
};
this class allows me to just instantiate my two classes Derived and Derived2
class Foo{
private:
Base * toto[2];
public:
Foo(){
toto[0] = new Derived;
toto[1] = new Derived2;
}
void doSomething();
}
and I want to do this
void Foo::doSomething(){
toto[0]->other();
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
last Question I create a new class inherited Derived2
and Base
class Derived3: public Derived2, public Base {
public:
Derived(int num);
void display(){cout <<"hello";}
void other();
};
now i want to do this
toto[0] = new Derived3
This my error message
Ambiguous conversion from derived class 'Derived3' to base class 'Base': class Derived3 -> class Base class Derived3 -> class Derived2 -> class Base
Assigning to 'Base *' from incompatible type 'Derived3 *'
Upvotes: 0
Views: 79
Reputation: 1961
You can use Dinamic cast: http://en.cppreference.com/w/cpp/language/dynamic_cast
void Foo::doSomething(){
Derived* e = dynamic_cast<Derived*>(toto[0]);
if (e != nullptr) //Did cast work?
e->other();
}
Upvotes: 2
Reputation: 119099
If toto[0]
is always going to point to Derived
and toto[1]
is always going to point to Derived2
, you should probably do this:
class Foo{
private:
Derived d1;
Derived2 d2;
Base * toto[2];
public:
Foo(){
toto[0] = &d1;
toto[1] = &d2;
}
void doSomething() {
d1.other();
}
};
If you really have a bona fide need to create a situation where typing cannot be statically checked, then use dynamic_cast
. But try to avoid that if possible. Don't treat C++ like a dynamically typed language.
Derived* dptr = dynamic_cast<Derived*>(toto[0]);
if (dptr) {
dptr->other();
} else {
throw std::logic_error("toto[0] should point to Derived");
}
Upvotes: 2