NyanPrime
NyanPrime

Reputation: 45

Access derived class' functions through pointer (C++)

Here's an example of the situation:

CAnimal *poTest = new CDog();

When I write "poTest->" All I can see are functions from the base class (in example: CAnimal) and not the ones in the derived one. How can I access these?

Upvotes: 0

Views: 529

Answers (6)

phooji
phooji

Reputation: 10395

Either define it as a dog:

 CDog *poTest = new CDog();

Or use a cast:

static_cast<CDog*>(poTest)->bark();

Or, as per some of the other answers use one of the other casting functions/operators. In general, however, making heavy use of casts is considered bad practice; this is one of the reasons why many mainstream languages offer generics (see e.g., here).

Upvotes: 0

Mark B
Mark B

Reputation: 96261

In general in such a case you should only be using the interface of the base class and that function wouldn't be accessible. If you're trying to use the derived interface, consider storing a pointer to CDog instead of CAnimal. Instead of trying to get to the child methods, make your parent interface appropriate.

If you really know that your pointer points to a dog you can downcast although this may be a design smell in some cases:

CDog* cdog = dynamic_cast<CDog *>(poTest);  // Safer
if(cdog)
{
    cdog->someFunction();
}

static_cast<CDog *>(poTest)->someFunction();   // Faster

Upvotes: 1

ildjarn
ildjarn

Reputation: 62975

dynamic_cast<CDog*>(poTest)->CDogSpecificFunction();

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

Since you declare poTest being an CAnimal, you can just call functions defined in CAnimal. Usually this is enougth since the base class should expose the method needed as virtual functions, dealing with a CAnimal instance and having to cast a CDog usually signal that there is something to improve in the design.

Upvotes: 0

Yochai Timmer
Yochai Timmer

Reputation: 49251

You've declared poTest as a CAnimal.

So it makes sense that you'll only see what a CAnimal can see.

If you want to use methods that a CDog uses, declare it so.

Upvotes: 4

Erik
Erik

Reputation: 91270

CDog * test = new CDog();
test->someFunction();


CAnimal *poTest = new CDog();
static_cast<CDog *>(poTest)->someFunction();

I'm assuming CDog (what's with the C prefix btw) inherits CAnimal. The compiler cannot know that your poTest variable happens to be a CDog - it can only see that it is a CAnimal. So, you can't call a member function of CDog with a variable of type CAnimal * - you need to convert the pointer to a CDog *, this tells the compiler to "treat this as a CDog".

Upvotes: 2

Related Questions