Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to call a parent class function from derived class function?

How would I call the parent function from an inferred class utilizing C++? For instance, I have a class called parent, and a class called kid which is gotten from a parent. Inside each class, there is a print function. In the meaning of the kid's print function, I might want to settle on a decision to the guardians print work. How might I approach doing this?
by

2 Answers

akshay1995
Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
virtual void print(int x);
};

class Child : public Parent {
void print(int x) override;
};

void Parent::print(int x) {
// some default behavior
}

void Child::print(int x) {
// use Parent's print method; implicitly passes 'this' to Parent::print
Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.
kshitijrana14
If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
printf("in Base\n");
}

void ChildOfBase::FooBar()
{
Base::FooBar();
}

Login / Signup to Answer the Question.