Call function from derived and base class - c++

#include <iostream>
class Base
{
public:
virtual ~Base() {}
virtual void f()
{
std::cout << "base\n";
}
};
class Derived : public Base
{
public:
virtual ~Derived() {}
virtual void f()
{
std::cout << "derived\n";
}
};
int main()
{
Derived* D = new Derived;
D->f();
delete D;
return 0;
}
So I am calling Derived::f but I want to call Base::f too. Is there any other way than calling Base::f() inside Derived::f()?

Sounds like what you want is a Non Virtual Interface (NVI) design. This is great when you want customization points (polymorphism, for example) for derived classes, but a somewhat guaranteed call flow.
class Base
{
public:
virtual ~Base() {}
void f()
{
// ... do something that always run before
f_impl();
// ... and after the extension point
}
protected:
virtual void f_impl()
{
}
};
class Derived : public Base
{
protected:
virtual void f_impl() override
{
std::cout << "extended!\n";
}
};
int main()
{
Derived d;
d.f(); // Base can _always_ run things before and after Derived
}

Related

How do I choose the base class when overriding a function in c++?

I have two base classes and a class that inherits both base classes.
Both base classes have a virtual function with the same signature, and I want to provide different implementations in the derived class to each virtual function.
class A{
virtual void f() = 0;
}
class B{
virtual void f() = 0;
}
class Derived:public A, public B{
void A::f() override{ // Error
...
}
void B::f() override{ // Error
...
}
}
What is the correct way to do this? (I cannot rename the virtual function. Actually the two base classes are generated from the same template class.)
template <typename T>
class AShim : public A {
void f() override {
static_cast<T*>(this)->A_f();
}
};
template <typename T>
class BShim : public B {
void f() override {
static_cast<T*>(this)->B_f();
}
};
class Derived: public AShim<Derived>, public BShim<Derived> {
void A_f();
void B_f();
};
class A {
public:
virtual void f() = 0;
};
class B {
public:
virtual void f() = 0;
};
class Derived :public A, public B {
public:
void A::f() {
cout << "Inside A's version"<<endl;
}
void B::f() {
cout << "Inside B's version"<<endl;
}
};
int main()
{
Derived derived;
cout << "calling A" << endl;
A *a;
a = &derived;
a->f();
cout << "calling B" << endl;
B *b;
b = &derived;
b->f();
}
Works fine for me. No need to explicitly mention override keyword as pure virtual functions will be overridden by virtue of its default properties.Use base class's scope while defining the functions as you have already done. Use public access specifier to enable derived classes to override the pure virtual function. That's all.

Access another Base Classes member from Abstract Base Class

I wonder if it is possible to declare a pure virtual function in class AbstractBase and make a Base classes member visible in Derived so it will use the member of Base and not look for a implementation in Derived. So far, i tried making Base's member visual by trying to use using but it won't compile since the look up, in this case, seems to ignore using. Is this possible at all? Here is my code:
#include <iostream>
using namespace std;
class AbstractBase {
public:
AbstractBase(){}
virtual ~AbstractBase(){}
protected:
virtual void f() = 0;
};
class Base {
public:
Base(){}
protected:
void f() {cout << "called Base's f()" << endl;}
};
class Derived : public Base, public AbstractBase {
public:
Derived(){}
//using Base::f; /*this won't compile*/
private:
void f(){} /*Access Base's f() here rather than implement*/
};
int main()
{
Derived d;
}
Use :: operator:
class Derived : public Base {
public:
Derived(){}
private:
void f(){ Base::f() }
};
Also, you don't need to inherit from AbstractBase.
It looks to me that you would like f() to be pure-virtual but provide default implementation. In this case, it can be achieved this way:
#include <iostream>
using namespace std;
struct AbstractBaseWithDefaultF
{
virtual ~AbstractBaseWithDefaultF() = default;
virtual void f() = 0;
};
void AbstractBaseWithDefaultF::f()
{
cout << "called AbstractBaseWithDefaultF's f()" << endl;
}
struct Derived : AbstractBaseWithDefaultF
{
void f() override
{
AbstractBaseWithDefaultF::f();
cout << "called Derived's f()" << endl;
}
};
int main()
{
Derived d;
d.f();
}
Output:
called AbstractBaseWithDefaultF's f()
called Derived's f()
Here's a live Wandbox example.

Why override under private inheritance?

class Base {
public:
virtual void f() {}
};
class Derived : private Base {
public:
void f() override {}
};
My question is there any use to such override? Private inheritance implies that you can not store Derived in Base pointer and thus it will never be needed to dynamically dispatch f to the correct type.
Just one example: A function of Derived::f1() can call a (public or protected) functions of Base::f2(), which in turn can call f(). In this case, dynamic dispatch is needed.
Here is an example code:
#include "iostream"
using namespace std;
class Base {
public:
virtual void f() {
cout << "Base::f() called.\n";
}
void f2() {
f(); // Here, a dynamic dispatch is done!
}
};
class Derived:private Base {
public:
void f() override {
cout << "Derived::f() called.\n";
}
void f1() {
Base::f2();
}
};
int main() {
Derived D;
D.f1();
Base B;
B.f2();
}
Output:
Derived::f() called
Base::f() called

A virtual function that must be overridden

Consider a base class class Base which has a function virtual void foo(void). This function is implemented in Base; i.e. is not pure virtual.
Is there a pattern I can use which when inheriting from this class, i.e. class Child : public Base, compels me to override foo?
Other than making it a pure virtual function, there is no way to make the override required.
Note that the fact that a function is marked pure virtual does not mean that it cannot have an implementation in the base class - it means only that the derived class must override it.
struct Base {
virtual void foo() = 0; // foo() is pure virtual
};
struct Derived : public Base {
void foo() { // Derived overrides the pure virtual
cout << "Hello ";
Base::foo(); // Call the implementation in the base
cout << endl;
}
};
void Base::foo() {
cout << " world";
}
int main() {
Derived d;
d.foo();
return 0;
}
This prints "Hello world", with the "world" part coming from the implementation in the base class.
Demo.
C++11 introduced the override keyword to help with this:
struct Base
{
void foo();
};
struct Derived : Base
{
void foo() override; // error! Base::foo is not virtual
};
However you can not write this in Base itself to get the same effect; i.e. there is no mustoverride specifier. Ultimately, it is none of Base's business as to what derived classes do or don't override.
You can keep Base abstract whilst providing a "default" definition for your pure virtual functions:
struct Base
{
virtual void foo() = 0;
};
void Base::foo() {}
struct Derived : Base {}; // error! does not override Base::foo
struct Derived2: Base
{
virtual void foo() override
{
Base::foo(); // invokes "default" definition
}
};
This will be an acceptable solution if you are content for the entire base type to be rendered uninstantiable.
A pure-virtual member function can still have a body. The only caveat is that it must be defined outside the class definition. This is perfectly legal C++:
#include <iostream>
struct Base
{
virtual void foo() const = 0;
};
void Base::foo() const
{
std::cout << "Base!\n";
}
struct Derived : Base
{
// Uncomment following line to remove error:
//virtual void foo() const override { std::cout << "Derived\n"; Base::foo(); }
};
int main()
{
Derived d;
d.foo();
}
Live example
Notice that this makes Base an abstract class in all respects, i.e. it's impossible to instantiate Base directly.
Yes, actually there is:
#include <iostream>
class Base
{
public:
virtual void someFun() {std::cout << "Base::fun" << std::endl;}
virtual ~Base() {}
};
class AlmostBase : public Base
{
public:
virtual void someFun() = 0;
};
class Derived : public AlmostBase
{
public:
virtual void someFun() {std::cout << "Derived::fun" << std::endl;}
};
int main()
{
Derived *d = new Derived();
d->someFun();
delete d;
}
If you uncomment the someFun from Derived the compiler will complain ...
You introduce an intermediary class AlmostBase which has the function as pure virtual. This way you can have Base objects too, and the only drawback now is that all your classes will need to inherit from the intermediary base.
you can make the base method throw an exception when called, then the class must override it to avoid the parent execution.
this is used in the MFC FrameWork for example
// Derived class is responsible for implementing these handlers
// for owner/self draw controls (except for the optional DeleteItem)
void CComboBox::DrawItem(LPDRAWITEMSTRUCT)
{ ASSERT(FALSE); }
void CComboBox::MeasureItem(LPMEASUREITEMSTRUCT)
{ ASSERT(FALSE); }
int CComboBox::CompareItem(LPCOMPAREITEMSTRUCT)
{ ASSERT(FALSE); return 0; }
those methods must be inherited if the control is owner drawn it is responsible for the measuer, draw,... if you missed it while you are testing the function you will get an assert or exception with useful information thrown.

How to call a base class's virtual function that is an input argument to a function

using C++, I have
struct Base {
virtual void stuff(/*base stuff*/);
};
struct Derived : public Base {
void stuff(/*derived stuff*/);
};
void function1(Derived& obj){
obj.stuff();
}
In this scenario, function1 will use Derived's do() function. What if in function1, I want to call the Base class's do() function instead ? Will it work if I call function1 as
function1(dynamic_cast<Base*>(derived_obj_ptr))?
After correcting the multitude of errors in your code, this is indeed achievable:
#include <iostream>
class Base {
public:
virtual void foo() { std::cout << "Base\n"; }
};
class Derived : public Base {
public:
void foo() { std::cout << "Derived\n"; }
};
void function1(Derived *p) {
p->Base::foo(); // <<<<< Here is the magic >>>>>
}
int main() {
Derived d;
function1(&d);
}
Output:
Base
(see http://ideone.com/FKFj8)