SPB
SPB

Reputation: 4218

How to access a child class function

class base{}

class child : public base{

**dummyfunction();**

}

now I am calling a function in which I am passing a child class object.

**child ob;**

function(**ob**);//calling a function  

//function body

function(**base *object**)
{

**//here I want to access the function of child class. How can I do it???**

 **for example dummyfunction()**

}

Upvotes: 2

Views: 3061

Answers (6)

Vikas
Vikas

Reputation: 179

Suppose the function you want to call is

void f(); 

Make it virtual in Base class and override in Derived class and then call it from inside any member function of the Base class (except constructor!).

Upvotes: 0

Ryan Badour
Ryan Badour

Reputation: 582

In addition to using dynamic cast you can use static_cast with references:

base &b = base();
static_cast<child&>(b).dummyFunction();

Upvotes: 1

TalentTuner
TalentTuner

Reputation: 17556

What you required is downcasting.

you can acheive by making the dummyFunction as virtual in base class and then overriding this function in child class this solution would not require downcasting

otherwise you can use the method described in the below post but this is not safe to downcast

Downcasting Method

Upvotes: 0

Yttrill
Yttrill

Reputation: 4921

Your desires are contrary to the purpose of the data structures you're using.

You can do it with

child *child_object = dynamic_cast<child*>(object);
child_object -> dummyfunction();

but you shouldn't. Try designing your system properly instead.

Upvotes: 1

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95489

You either need to put the function in the base class and make it virtual, or you need to do a type-safe down cast, using dynamic_cast. It is probably better to make the function a part of the interface, and have it available both in the base class and in the child class, but without more information it's hard to say. Generally speaking, though, the use of RTTI and dynamic_cast are indicative of poor design.

Upvotes: 4

Falmarri
Falmarri

Reputation: 48567

Why would you want to do this? If you're taking in an object of class base, you can't call a function of class child.

Upvotes: 3

Related Questions