Return child class into base class object - c++

I am trying to get my head around some inheritance problem in C++:
Consider a base class Foo() with a method method() and its derived class Bar. Now I override the method in Bar.
class Foo{
public:
double method();
}
class Bar public: Foo
{
public:
double method()
}
And a function like this:
Foo get_bar(){
Bar bar()
return bar
}
Calling the function get_bar() I'd like to be able to call Bar::method()
Foo foo = get_bar();
foo.method() (-> which should be Bar::method)
Is this possible? And if, how? I think I am making a fundamental mistake here which I don't see. Thanks!

To override (not overwrite) a function, it must be virtual:
class Foo {
public:
virtual void method();
virtual ~Foo() = default; // technically optional, but usually needed
};
For completeness, here is the corrected syntax for the derived class:
class Bar : public Foo {
public:
void method() override; // override is optional, but a good idea
};
Polymorphism only works on references and pointers, so your function would have to return one of those, not a base-class object. As it is (once the syntax is fixed), it slices the Bar object to return a copy of its Foo, which would not give you the overridden function that you want.
There's no existing object to return a reference to; so you'll probably have to dynamically create one an return a pointer. Unless you enjoy long debugging sessions, use smart pointers to manage dynamic objects:
std::unique_ptr<Foo> get_bar() {
return std::unique_ptr<Foo>(new Bar); // C++14: make_unique<Bar>();
}

If I understand your question correctly you want get_bar() to return a child class Bar as if it was the base class Foo such that you can subsequently call method on it and it will call Bar::method(). Yes, you can do that. It is called Polymorphism.
In order to achieve this get_bar() needs to return a pointer otherwise you will encounter the slicing problem and won't get the polymorphic behaviour you are looking for. As get_bar() is a factory function transferring ownership to the caller it is preferable to return a smart-pointer like unique_ptr or shared_ptr:
std::unique_ptr<Foo> getBar() {
return std::make_unique<Bar>();
}
Foo::method() needs to be virtual in order to override it in Bar. And in order to destroy Bar properly when the Foo pointer is deleted Foo must have a virtual destructor:
class Foo {
public:
virtual void method();
virtual ~Foo(){}
};
class Bar : public Foo {
public:
void method() override;
};

Related

Saving abstract value object in wrapper and Usage of inheritance

I have issues regarding C++ class inheritance.
I have a class which has virtual method, for example:
class IFoo {
public:
virtual int sayFoo() = 0;
};
And I have several implementations, for example:
class Foo1: public IFoo {
public:
virtual int sayFoo() {
return 1;
}
};
class Foo2: public IFoo {
public:
virtual int sayFoo() {
return 2;
}
};
I want to hold IFoo instance inside a dummy container class (like a sort of wrapper) exposing the same interface of IFoo:
class DummyWrapper : public IFoo {
public:
DummyWrapper(IFoo& foo): foo{foo} {}
virtual int sayFoo() {
return foo.sayFoo(); //ALPHA
}
private:
IFoo& foo; //BETA
};
Normally everything should work, for example, like this:
IFoo& foo = Foo1{};
DummyWrapper wrapper{foo};
wrapper.sayFoo();
My problem is that foo is actually just a r-value that is removed after its scope goes out, like here:
DummyWrapper generateWrapper() {
return DummyWrapper{Foo1{}};
}
This lead to read problems in "ALPHA" line.
A solution would be to put the r-value on the heap and use pointers to access the foo. Since I'm new to C++ and maybe I'm falling into a XY problem, my question is:
is this the only solution? Isn't there a better method to use to solve the issue?
I don't think i can replace "BETA" line with IFoo foo since in this way the DummyWrapper will always store the bytes of a IFoo, not of a IFoo implementation. Or maybe I can use the value IFoo foo to call derived virtual methods?
Thanks for any kind reply
is this the only solution? Isn't there a better method to use to solve the issue?
As soon as polymorphism is involved, unfortunately, yes, it is and no, there isn't. But you get an almost equivalent solution to storing IFoo foo, if you use a smart pointer:
// member:
std::unique_ptr<IFoo> foo;
// constructor:
DummyWrapper(std::unique_ptr<IFoo>&& foo): foo(std::move(foo)) { }
// need to accept r-value ^
// reference: std::unique_ptr is only movable, not copiable!
// for the same reason, you need to preserve the r-value reference
// on assignment to member...
// creation of the wrapper:
return DummyWrapper(std::make_unique<Foo1>(/* arguments for constructor, if there are */));
I don't think i can replace "BETA" line with IFoo foo since in this way the DummyWrapper will always store the bytes of a IFoo, not of a IFoo implementation. Or maybe I can use the value IFoo foo to call derived virtual methods?
Absolutely correct: That's an effect called 'object slicing', at the point you assign a derived object to a base one, all the surplus stuff coming from the derived type gets lost. Pretty common problem (e. g. when people try to store derived objects in a std::vector<Base>).
Usually we create wrapper when we wants to alter the interface of a class or want to implement additional functionalities, for example
std::queue<T> is wrapper/adapter on std::std::deque<T>(by default)
The std::queue<T> class template acts as a wrapper to the underlying container - only a specific set of functions is provided. The queue pushes the elements on the back of the underlying container and pops them from the front.
In your case i don't think you need DummyWrapper you can use IFoo in place of DummyWrapper and it will do the same job.
Let consider following function,
bool isEven( IFoo& ifoo) // Not const& because sayFoo() is not const method.
{
return ( 0 == ( ifoo.sayFoo() % 2)) ;
}
This function will work for all types like Foo1 , Foo2, and no wrapper is required.

C++: Override method which has the same name as the class

Let's say I have a nice looking base class called base:
class base
{
public:
virtual void foo() const = 0;
};
Now, I have a class named foo that I would like to inherit from base and override base::foo:
class foo : public base
{
public:
virtual void foo() const override;
};
This is illegal in C++, as you are not allowed to name a method the same thing as the class (C++ greedily believes methods with the same name as the class are constructors, which are not allowed to have return types). Is there any way around this that doesn't involve changing the name of the class or method? I want external users to be able to create foo classes without the knowledge that there is a method base::foo called by someone else (imagine foo can be both a noun and a verb).
Is there any way around this that doesn't involve changing the name of the class or method?
No, there isn't.
All methods named foo are special in class foo -- they are constructors. Hence, they cannot be overridden virtual member functions.
I'll take a wild guess and just say NO.
You can have a lot of ambiguities in C++ (that sometimes have to be explicitly disambiguated), but I don't even see a way how a compiler or programmer could disambiguate this situation. Well, A programmer can (a function with a return type is obviously not a constructor), but C++ can't.
In C++, the only method that can have the class' name is its constructor.
So, no. You can't.
Okay, here's my (slightly evil) solution...
// Create an intermediate class which actually implements the foo method:
class foo_intermediate : public base
{
public:
virtual void foo() const override;
};
// Derive from that class and forward the constructor along
class foo : public foo_intermediate
{
public:
using foo_intermediate::foo_intermediate;
private:
friend class foo_intermediate;
// Actual implementation for the foo function goes here
void foo_impl() const;
};
// In some CPP file:
void foo_intermediate::foo() const
{
// Need to access the typename foo via namespace (global here)
static_cast<const ::foo*>(this)->foo_impl();
}
Actually calling foo is a bit funny, since this can't work:
void bar()
{
foo x;
x.foo(); // <- illegal attempt to access to the foo constructor
}
You must access through an alias:
void baz()
{
foo x;
base& rx = x;
rx.foo(); // legal
}
As an alternative, you can use a typedef:
class foo_impl : public base
{
public:
virtual void foo() const override;
};
using foo = foo_impl;
This gets around the issue of calling x.foo(), since it no longer appears as a constructor access.
I made a Gist so others could play with the two solutions if they are so inclined.

Virtual Function During Construction Workaround

I've got a base class that has a virtual function. I want to call that class during the construction because I want the function called for each of the derived classes. I know I can't call a virtual function during construction, but I can't think of an elegant (i.e., avoid repeating code) solution.
What are some work arounds to calling a virtual function during construction?
The reason I want to avoid this is because I don't want to have to create constructors that just call the base class.
class A {
public:
A() {
read();
}
// This never needs to be called
virtual void read() = 0;
}
class B:A {
public:
B():A() { };
read() { /*Do something special for B here.*/ }
}
class C:A {
public:
C():A() { };
read() { /*Do something special for C here.*/ }
}
PS: The Python way of doing this is simply to raise NotImplementedError in A::read(). I'm returning to C++ and I'm more rusty than I thought.
The FAQ perspective.
This is a Frequently Asked Question.
See the C++ FAQ item titled “Okay, but is there a way to simulate that behavior as if dynamic binding worked on the this object within my base class's constructor?”.
It’s very often a good idea to check the FAQ (and generally, googling or altavista’ing) before asking.
The question as “Derived class specific base initialization”.
To be clear, while the literal question above is
“What are some work arounds to calling a virtual function during construction?”
it is evident that what’s meant is
“How can a base class B be designed so that each derived class can specify part of what goes on during B construction?”
A major example is where C style GUI functionality is wrapped by C++ classes. Then a general Widget constructor might need to instantiate an API-level widget which, depending on the most derived class, should be a button widget or a listbox widget or whatever. So the most derived class must somehow influence what goes on up in Widget’s constructor.
In other words, we’re talking about derived class specific base construction.
Marshall Cline called that “Dynamic Binding During Construction”, and it’s problematic in C++ because in C++ the dynamic type of an object during class T construction and destruction, is T. This helps with type safety, in that a virtual member function is not called on a derived class sub-object before that sub-object has been initialized, or its initialization has started. But a major cost is that DBDI (apparently) can’t be done in a way that is both simple and safe.
Where the derived class specific init can be performed.
In the question the derived class specific action is called read. Here I call it derived_action. There are 3 main possibilities for where the derived_action is invoked:
Invoked by instantiation code, called two-phase construction.
This essentially implies the possibility of having a mostly unusuable not fully initialized object at hand, a zombie object. However, with C++11 move semantics that has become more common and accepted (and anyway it can be mitigated to some extent by using factories). A main problem is that during the second phase of construction the ordinary C++ protection against virtual calls on uninitialized sub-objects, due to dynamic type changes during construction, is not present.
Invoked by Derived constructor.
For example, derived_action can be invoked as an argument expression for the Base constructor. A not totally uncommon technique is to use a class template to generate most derived classes that e.g. supply calls of derived_action.
Invoked by Base constructor.
This implies that knowledge of derived_action must be passed up to the constructor, dynamically or statically. A nice way is to use a defaulted constructor argument. This leads to the notion of a parallel class hierarchy, a hierarchy of derived class actions.
This list is in order of increasing sophistication and type safety, and also, to the best of my knowledge, reflects the historical use of the various techniques.
E.g. in Microsoft’s MFC and Borland’s ObjectWindows GUI early 1990’ libraries two-phase construction was common, and that kind of design is now, as of 2014, regarded as very ungood.
This is the factory method approach, putting the factory into the base class:
class A {
public:
virtual void read() = 0;
template<class X> static X* create() {X* r = new X;X->read();return X;}
virtual A* clone() const = 0;
};
class B : public A {
B():A() { };
friend class A;
public:
void read() { /*Do something special for B here.*/ }
B* clone() const {return new B(*this);}
};
class C : public A {
C():A() { };
friend class A;
public:
void read() { /*Do something special for C here.*/ }
C* clone() const {return new C(*this);}
};
Added a clone-method with covariant return type as a bonus.
Using CRTP:
class A {
public:
// This never needs to be called
virtual void read() = 0;
virtual A* clone() const = 0;
};
template<class D, class B> struct CRTP : B {
D* clone() {return new D(*this);}
static D* create() {return new D();}
};
class B : public CRTP<B, A> {
B() { };
public:
void read() { /*Do something special for B here.*/ }
};
class C : public CRTP<C, A> {
C() { };
public:
void read() { /*Do something special for C here.*/ }
};
One way to achieve this, would be simply to delegate it to another class (that is perhaps a friend) and can be sure to be called when fully constructed.
class A
{
friend class C;
private:
C& _c; // this is the actual class!
public:
A(C& c) : _c(c) { };
virtual ~A() { };
virtual void read() = 0;
};
class B : public A
{
public:
B(C& c) : A(c) { };
virtual ~B() { };
virtual void read() {
// actual implementation
};
};
class C
{
private:
std::unique_ptr<A> _a;
public:
C() : _a(new B(*this)) { // looks dangerous? not at this point...
_a->read(); // safe now
};
};
In this example, I just create a B, but how you do that can depend on what you want to achieve and use templates on C if necessary, e.g:
template<typename VIRTUAL>
class C
{
private:
using Ptr = std::unique_ptr<VIRTUAL>;
Ptr _ptr;
public:
C() : _ptr(new VIRTUAL(*this)) {
_ptr->read();
};
}; // eo class C
The workaround is to call the virtual function after construction. You can then couple the two operations (construction + virtual call) in factory function. Here is the basic idea:
class FactoryA
{
public:
A *MakeA() const
{
A *ptr = CreateA();
ptr->read();
return ptr;
}
virtual ~FactoryA() {}
private:
virtual A *CreateA() const = 0;
};
class FactoryB : public FactoryA
{
private:
virtual A *CreateA() const { return new B; }
};
// client code:
void f(FactoryA &factory)
{
A *ptr = factory.MakeA();
}
As mentioned by Benjamin Bannier, you can use CRTP (a template which defines the actual read() function.) One problem with that method is that templates have to always be written inline. That can at times be problematic, especially if you are to write really large functions.
Another way is to pass a function pointer to the constructor. Although, in a way, it is similar to calling the function in your constructor, it forces you to pass a pointer (although in C++ you could always pass nullptr.)
class A
{
public:
A(func_t f)
{
// if(!f) throw ...;
(*f)();
}
};
class B : A
{
public:
B() : A(read) {}
void read() { ... }
};
Obviously, you have the "can't call other virtual functions" problem within the read() function and any function it calls. Plus, variable members of B are NOT yet initialized. That is probably a much worst problem in this case...
For that reason, writing it this way is safer:
B() : A()
{
read();
}
However, in cases like that, that may be the time when you an some for of init() function. That init() function can be implemented in A() (if you make it accessible: i.e. use public A when deriving) and that function can call all the virtual functions as expected:
class A
{
public:
void init()
{
read();
}
};
class B : public A
{
public:
...
};
I know a lot of people say that an init() function is evil because people who create a B object now need to know to call it... but there isn't much else you can do. That being said, you could have a form of factory, and that factory can do the init() call as required.
class B : public A
{
public:
static B *create() { B *b(new B); b->init(); return b; }
private:
B() { ... } // prevent creation without calling create()
};

Function overriding in C++ works without 'virtual'

I have a class that contains some functions (none are virtual) and 2 more classes publicly inherit that class. In both the sub classes I override the same function of the base class.
After creating objects of all three classes in main (located at the same file), I call the original function with the baseclass object and the overridden functions with the derivedclass objects.
I was expecting all 3 function calls to run the original function from the base class (since I didn't use 'virtual' anywhere in the code), but I actually get each version of that function working according to the class in which it was defined (3 different versions).
I have the classes Base & Derived as follows:
struct Base
{
void foo();
};
struct Derived : Base
{
void foo();
};
in main:
int main()
{
Derived d;
d.foo();
}
I thought d.foo() should run Base::foo() if not using 'virtual'.
This is not "overriding"... and it doesn't need to be.
struct Base
{
void foo();
};
struct Derived : Base
{
void foo();
};
int main()
{
Derived d;
d.foo();
}
If I understand you correctly, then you were expecting this to execute Base::foo(), because the functions are not virtual and therefore one does not override the other.
But, here, you do not need virtual dispatch: the rules of inheritance simply state that you'll get the right function for the type of the object you run it on.
When you need virtual dispatch/overriding is a slightly different case: it's when you use indirection:
int main()
{
Base* ptr = new Derived();
ptr->foo();
delete ptr;
}
In the above snippet, the result will be that Base::foo() is called, because the expression ptr->foo() doesn't know that *ptr is really a Derived. All it knows is that ptr is a Base*.
This is where adding virtual (and, in doing so, making the one function override the other) makes magic happen.
You cannot override something that isn't virtual. Non-virtual member functions are dispatched statically based on the type of the instance object.
You could cheat by "overriding" a function by making it an inline function calling something indirectly. Something like (in C++03)
class Foo;
typedef int foo_sig_t (Foo&, std::string&);
class Foo {
foo_sig_t *funptr;
public:
int do_fun(std::string&s) { return funptr(*this,s); }
Foo (foo_sig_t* fun): funptr(fun) {};
~Foo () { funptr= NULL; };
// etc
};
class Bar : public Foo {
static int barfun(Bar&, std::string& s) {
std::cout << s << std::endl;
return (int) s.size();
};
public:
Bar () : Foo(reinterpret_cast<foo_sig_t*>)(&barfun)) {};
// etc...
};
and later:
Bar b;
int x=b.do_fun("hello");
Officially this is not overloading a virtual function, but it looks very close to one. However, in my above Foo example each Foo instance has its own funptr, which is not necessarily shared by a class. But all Bar instances share the same funptr pointing to the same barfun.
BTW, using C++11 lambda anonymous functions (internally implemented as closures), that would be simpler and shorter.
Of course, virtual functions are in generally in fact implemented by a similar mechanism: objects (with some virtual stuff) implicitly start with a hidden field (perhaps "named" _vptr) giving the vtable (or virtual method table).

Overwrite one method in c++ class

If I have this class:
class FooBar {
public:
FooBar(int qux);
void bar();
void foo1();
void foo2();
//...
void foo99();
}
How can I overwrite the bar method in FooBar, while still being able to use all the other foo method without defining them again?
Edit:
I want to use like this:
FooBar2 baz(1); // call the constructor of FooBar, FooBar(1)
baz.foo1(); //call method foo1 of original FooBar
baz.bar(); // call method bar of FooBar2
I prefer not to edit the header or implementation of FooBar.
Is it also possible to make the constructor function call the original constructor function from FooBar?
You make bar virtual, because overriding only applies to virtual methods.
Then you extend FooBar and provide a new implementation just for bar.
class FooBar {
public:
virtual void bar();
void foo1();
void foo2();
//...
void foo99();
};
class FooBarDerived : FooBar
{
public:
void bar();
};
Inheritance.
class FooBar
{
public:
virtual void bar() { ... default implementation ... }
void foo1();
void foo99();
}
class FooBarVariation : public FooBar
{
public:
virtual void bar() { ... different implementation ... }
}
FooBarVariation will act like a FooBar, but with a different implementation of bar().
What you need is Function Hiding and not overridding.
Overidding applies only when the virtual keyword is involved.
Just redefine the method you want to overload in your derived class and you should be fine.
class YourClass: public FooBar
{
public:
void bar(){}
};
The class YourClass objects can access all the methods of FooBar because those are public methods and your class derives publically from it, while YourClass::bar() hides FooBar::bar().
EDIT:
Your edited question makes it clear that Function Hiding is indeed what you need.
Here is a online demo of function hiding achieving what your requirement is.
Is it also possible to make the constructor function call the original constructor function from FooBar?
You can use the Member Initialization list to call appropriate Base class constructor through derived class constructor.
Good Read:
What is this weird colon-member (" : ") syntax in the constructor?