peyman
peyman

Reputation: 21

How to refer to a method defined in a derived class only, using an upcast unique_ptr pointer in C++?

Assume following classes

class Base
{
   void Doajob(a,b){...}
}

class Derived: public Base
{
   void Doanotherjob(a,b,c){...}
}

I have defined a pointer as follows:

 auto ptr= unique_ptr<Base>(new Derived(name));

Now I want to access Doanotherjob using the ptr pointer:

ptr->Doanotherjob(a,b,c); // ERROR
((unique_ptr<Base>) ptr)->Doanotherjob(a,b,c); // ERROR
((unique_ptr<Derived>) ptr)->Doanotherjob(a,b,c); // ERROR

Is that even a right thing to do? What is the syntax?

Upvotes: 1

Views: 194

Answers (1)

Chad
Chad

Reputation: 19032

If you know for sure that the downcast is safe, you can use static_cast.

static_cast<derived*>(ptr.get())->DoAnotherJob(...);

However, if you made DoAnotherJob() virtual in base, then the downcast is unnecessary. This is a much more traditional object-oriented approach.

As stated in the comments below, dynamic_cast let's you do this cast and verify the result:

if(auto d = dynamic_cast<derived*>(ptr.get())
   d->DoAnotherJob();

Upvotes: 5

Related Questions