1

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?

5
  • 1
    On a side note, downcasting to a derived class violates LSP and is usually indicative of a flaw in your design. Commented Mar 30, 2015 at 21:00
  • Even with a regular pointer you wouldn't able to make this call, unless via a downcast, since you don't access an overridden function Commented Mar 30, 2015 at 21:04
  • Base must have a virtual destructor, otherwise the unique_ptr will cause UB when it tries to delete the pointer Commented Mar 31, 2015 at 21:01
  • I guess you meant to derive Derived from Base, rather than from itself Commented Mar 31, 2015 at 21:02
  • Yes, I changed the word Derived to Base. Commented Apr 1, 2015 at 14:15

1 Answer 1

5

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();
Sign up to request clarification or add additional context in comments.

4 Comments

perhaps dynamic_cast as it allows you to test whether the result is ok?
I could not make 'code' DoAnotherjob() virtual in base as type of c is not defined in Base. I tried making a virtual DoAnotherjob(TypeofA a,TypeofB b, vector<Derived::TypeofCelement> c) but it did not work. So I tried to bypass the Base class criteria and send the arguments directly to the derived class. Also I have a container of pointers to Base class which may or may not be possible to be downcasted to derive class. I think I can use dynamic_cast o check as above mentioned. Am I right?
Yes dynamic_cast in the example above will return nullptr if the conversion fails so the body of the if statement will not be executed in that case.
The dynamic_cast version will only work if Base has a virtual function. However using the unique_ptr is UB anyway if Base did not have a virtual destructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.