class Foo
{
public:
void action();
};
class Bar : public Foo
{
public:
void action();
};
void Foo::action ()
{
cout << "parent\n";
};
void Bar::action ()
{
cout << "child\n";
};
int main()
{
Foo* foo = new Bar ();
foo->action(); // returns "parent" - "child" expected
return 1;
}
I'm sorry for a probably trivial question, but I'm new to C++...
The 'foo' pointer must point to an instance of Foo class, since it can be any of Foo's childs e.g. Bar, Bar1, Bar2, Bar3 etc.
And at the same time 'foo->action()' should run an overridden function of the child.
Tell me please, how do I correct the code to reach my goals...
Thanks!
Unlike other languages, like Java, in C++ base class have to specifically mark the methods it allows overriding of by using keyword virtual
The member function needs to be declared virtual (unlike Java for example, where all methods are implicitly virtual):
class Foo
{
public:
virtual void action();
};
Use keyword virtual for parent-class function. And also, your parent class should have virtual destructor.
class Foo
{
public:
virtual void action();
};
class Bar : public Foo
{
public:
void action();
};
void Foo::action ()
{
cout << "parent\n";
};
void Bar::action ()
{
cout << "child\n";
};
int main()
{
Foo* foo = new Bar ();
foo->action(); // returns "parent" - "child" expected
return 1;
}
Related
My aim is to have a class that inherits from another class in C++ and overloads all of the parents class methods in an identical fashion.
So when a method is called some code is run, the original method is called and a bit more code is run all in the derived class overload method.
class Base
{
Base() {}
~Base() {}
void base_method()
{
// Does something.
}
}
template<class T>
class ClassWrapper : public T
{
public:
ClassWrapper(T base) : T( base ) {}
~ClassWrapper() {}
void wrap_function()
{
// multithread block {
// call base method within multithread block.
this->base_method();
// }
}
}
int main()
{
Base B;
ClassWrapper<Base> C( B );
C.base_method();
return 0;
}
Ideally nothing would be known about the base class but all of its methods could be overridden.
I'm not sure if this is even possible but if it is any suggestions would be great!
With inheritance, you might do:
class Base
{
Base() {}
virtual ~Base() {}
virtual void base_method()
{
// Does something.
}
};
class BaseWrapper : public Base
{
public:
BaseWrapper(Base base) : Bas( base ) {}
void base_method() override
{
// Some code ...
Base::base_method();
// Some code ...
}
}
int main()
{
Base B;
BaseWrapper C( B );
C.base_method();
}
Static polymorphism achieved through CRTP (Curiously Recurring Template Pattern) might be beneficial for you.
Read more about CRTP here and here.
Imagine you have a Wrapper class like:
template <typename Impl>
class Wrapper {
public:
Wrapper() {}
~Wrapper() {}
void some_preparation() {
std::cout << "Wrapper work!" << std::endl;
}
};
and then you have your actual class like:
class MyFoo : public Wrapper<MyFoo> {
public:
MyFoo() {}
~MyFoo() {}
void foo() {
Wrapper::some_preparation();
std::cout << "Derived work!" << std::endl;
}
};
and, eventually, you can use above code like:
MyFoo wrappedFoo;
wrappedFoo.foo();
The result would be:
Wrapper work!
Derived work!
Jarod's answer is a very good one for your question. However, I would like to add an answer more focused on your chosen design rather than the implementation.
Although you said that you want to "overloads all of the parents class methods in an identical fashion", your goal ("the original method is called and a bit more code is run all in the derived class overload method") indicates that it is slightly different.
The first one may indicate inheritance, but the second one may point to factory abstract design pattern (composition over inheritance):
#include<iostream>
class AbstractBar
{
public:
virtual void bar_method() = 0;
};
class Bar1 : public AbstractBar
{
public:
void bar_method() {
std::cout << "Bar 1" << std::endl;
}
};
class Bar2 : public AbstractBar
{
public:
void bar_method() {
std::cout << "Bar 2" << std::endl;
}
};
class Foo
{
public:
Foo(AbstractBar* bar_) : bar(bar_) { }
void foo_method() {
bar->bar_method();
std::cout << "Foo" << std::endl;
}
private:
AbstractBar* bar;
};
int main() {
Bar1 bar;
Foo foo(&bar);
foo.foo_method();
}
Being the output of the code:
Bar 1
Foo
Or a simplified version (based on your needs):
#include<iostream>
class Bar {
public:
void bar_method() {
std::cout << "Bar" << std::endl;
}
};
class Foo {
public:
Foo(Bar* bar_) : bar(bar_) { }
void foo_method() {
bar->bar_method();
std::cout << "Foo" << std::endl;
}
private:
Bar* bar;
};
int main() {
Bar bar;
Foo foo(&bar);
foo.foo_method();
}
How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within
each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
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.
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();
}
In MSVC there is a Microsoft specific keyword for that: __super
MSDN:
Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.
// deriv_super.cpp
// compile with: /c
struct B1 {
void mf(int) {}
};
struct B2 {
void mf(short) {}
void mf(char) {}
};
struct D : B1, B2 {
void mf(short) {
__super::mf(1); // Calls B1::mf(int)
__super::mf('s'); // Calls B2::mf(char)
}
};
If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class.
Call to the base class non-virtual and virtual member function from derived member function can be made.
Please refer the program.
#include<iostream>
using namespace std;
class Parent
{
protected:
virtual void fun(int i)
{
cout<<"Parent::fun functionality write here"<<endl;
}
void fun1(int i)
{
cout<<"Parent::fun1 functionality write here"<<endl;
}
void fun2()
{
cout<<"Parent::fun3 functionality write here"<<endl;
}
};
class Child:public Parent
{
public:
virtual void fun(int i)
{
cout<<"Child::fun partial functionality write here"<<endl;
Parent::fun(++i);
Parent::fun2();
}
void fun1(int i)
{
cout<<"Child::fun1 partial functionality write here"<<endl;
Parent::fun1(++i);
}
};
int main()
{
Child d1;
d1.fun(1);
d1.fun1(2);
return 0;
}
Output:
$ g++ base_function_call_from_derived.cpp
$ ./a.out
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
struct a{
int x;
struct son{
a* _parent;
void test(){
_parent->x=1; //success
}
}_son;
}_a;
int main(){
_a._son._parent=&_a;
_a._son.test();
}
Reference example.
I'm attempting to do method chaining, however, instead of using the Methods in "Foo" I want to a constructor of a class (which is inherited from the base class):
class Bar {
public:
Bar() {
std::cout << "This is bar";
}
};
class Foo : public Bar {
public:
Foo() {
cout << "This is foo";
}
};
So my main would look like the following:
Foo f = Foo().Bar();
Why is this not possible in C++/C++11? Also, is there a way in which I can integrate this standard, or would I have to create an method in "Foo" which calls the constructor to "Bar"?
Edit:
class Bar {
public:
Bar() {
}
Bar& Options() {
cout << "sf";
return *this;
}
};
class Foo : public Bar {
public:
Foo() {
}
};
And then in main:
Foo F = Foo().Options();
Your updated question is illegal because Bar::Options() returns a reference to a Bar and you don't provide a way to convert a Bar to a Foo object.
I am experiencing a problem where a derived class does not have it's own version of a function called when it is called from a base class pointer. To better explain the classes are defined as below
Class Foo
{
public:
Foo();
virtual ~Foo();
virtual void Event();
}
//-----------------------
Class FooBar : public Foo
{
public:
FooBar();
virtual void Update() = 0;
virtual void Draw() = 0;
}
//-----------------------
Class FinalFoo : public FooBar
{
public:
FinalFoo();
void Update();
void Draw();
void Event();
}
There are other classes similar to FinalFoo. So I attempt to call Event on a pointer to a Foo object expecting that it would call the derived implementation. However, it would appear that it calls the base class version and that is all
FinalFoo* myThing = new FinalFoo();
Foo* baseThing = myThing;
baseThing->Event(); // I expected this to call FinalFoo::Event()
Assuming the above code is corrected, it actually does call FinalFoo::Event(). below is a complete and compilable example. Note, that it also adds the keyword override in strategic points: I'd bet that adding override in the original code, too (and compiling with a compiler aware of this keyword) would point out that your override isn't one.
#include <iostream>
class Foo
{
public:
virtual ~Foo() {}
virtual void Event() { std::cout << "Foo::Event()\n"; }
};
//-----------------------
class FooBar : public Foo
{
public:
virtual void Update() = 0;
};
//-----------------------
class FinalFoo : public FooBar
{
public:
FinalFoo() {}
void Update() override { std::cout << "FinalFoo::Update()\n"; }
void Event() override { std::cout << "FinalFoo::Event()\n"; }
};
int main()
{
FinalFoo myThing;
Foo* baseThing = &myThing;
baseThing->Event();
}
Say I have classes Foo and Bar set up like this:
class Foo
{
public:
int x;
virtual void printStuff()
{
std::cout << x << std::endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
// I would like to call Foo.printStuff() here...
std::cout << y << std::endl;
}
};
As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the super.funcname() syntax. Is this possible in C++?
In C++ you have to explicitly name the base class in calling the derived class method. This can be done from any method from the derived class. The override is a special case of the method of the same name. In Java there is no multi inheritance, so you can use super which will uniquely name the base class. The C++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() override { // help the compiler to check
Foo::printStuff(); // calls base class' function
}
};
Yes,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
It is the same as super in Java, except it allows calling implementations from different bases when you have multiple inheritance.
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
Sometimes you need to call the base class' implementation, when you aren't in the derived function...It still works:
struct Base
{
virtual int Foo()
{
return -1;
}
};
struct Derived : public Base
{
virtual int Foo()
{
return -2;
}
};
int main(int argc, char* argv[])
{
Base *x = new Derived;
ASSERT(-2 == x->Foo());
//syntax is trippy but it works
ASSERT(-1 == x->Base::Foo());
return 0;
}
Just in case you do this for a lot of functions in your class:
class Foo {
public:
virtual void f1() {
// ...
}
virtual void f2() {
// ...
}
//...
};
class Bar : public Foo {
private:
typedef Foo super;
public:
void f1() {
super::f1();
}
};
This might save a bit of writing if you want to rename Foo.
If you want to call a function of base class from its derived class you can simply call inside the overridden function with mentioning base class name(like Foo::printStuff()).
code goes here
#include <iostream>
using namespace std;
class Foo
{
public:
int x;
virtual void printStuff()
{
cout<<"Base Foo printStuff called"<<endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
cout<<"derived Bar printStuff called"<<endl;
Foo::printStuff();/////also called the base class method
}
};
int main()
{
Bar *b=new Bar;
b->printStuff();
}
Again you can determine at runtime which function to call using the object of that class(derived or base).But this requires your function at base class must be marked as virtual.
code below
#include <iostream>
using namespace std;
class Foo
{
public:
int x;
virtual void printStuff()
{
cout<<"Base Foo printStuff called"<<endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
cout<<"derived Bar printStuff called"<<endl;
}
};
int main()
{
Foo *foo=new Foo;
foo->printStuff();/////this call the base function
foo=new Bar;
foo->printStuff();
}
If there are multiple levels of inheritance, you can specify the direct base class, even if the actual implementation is at a lower level.
class Foo
{
public:
virtual void DoStuff ()
{
}
};
class Bar : public Foo
{
};
class Baz : public Bar
{
public:
void DoStuff ()
{
Bar::DoStuff() ;
}
};
In this example, the class Baz specifies Bar::DoStuff() although the class Bar does not contain an implementation of DoStuff. That is a detail, which Baz does not need to know.
It is clearly a better practice to call Bar::DoStuff than Foo::DoStuff, in case a later version of Bar also overrides this method.
check this...
#include <stdio.h>
class Base {
public:
virtual void gogo(int a) { printf(" Base :: gogo (int) \n"); };
virtual void gogo1(int a) { printf(" Base :: gogo1 (int) \n"); };
void gogo2(int a) { printf(" Base :: gogo2 (int) \n"); };
void gogo3(int a) { printf(" Base :: gogo3 (int) \n"); };
};
class Derived : protected Base {
public:
virtual void gogo(int a) { printf(" Derived :: gogo (int) \n"); };
void gogo1(int a) { printf(" Derived :: gogo1 (int) \n"); };
virtual void gogo2(int a) { printf(" Derived :: gogo2 (int) \n"); };
void gogo3(int a) { printf(" Derived :: gogo3 (int) \n"); };
};
int main() {
std::cout << "Derived" << std::endl;
auto obj = new Derived ;
obj->gogo(7);
obj->gogo1(7);
obj->gogo2(7);
obj->gogo3(7);
std::cout << "Base" << std::endl;
auto base = (Base*)obj;
base->gogo(7);
base->gogo1(7);
base->gogo2(7);
base->gogo3(7);
std::string s;
std::cout << "press any key to exit" << std::endl;
std::cin >> s;
return 0;
}
output
Derived
Derived :: gogo (int)
Derived :: gogo1 (int)
Derived :: gogo2 (int)
Derived :: gogo3 (int)
Base
Derived :: gogo (int)
Derived :: gogo1 (int)
Base :: gogo2 (int)
Base :: gogo3 (int)
press any key to exit
the best way is using the base::function as say #sth
Yes you can call it. C++ syntax for calling parent class function in child class is
class child: public parent {
// ...
void methodName() {
parent::methodName(); // calls Parent class' function
}
};
Read more about function overriding.