If the base class contains a member function let’s say callme and derived class overrides it, calling .calllme on derived class object would call the override function.
#include <iostream>
class Base
{
int m_base{};
public:
Base(int value = 5)
: m_base{value}
{
std::cout << "Creating base" << '\n';
}
void identify()
{
std::cout << "From base class" << '\n';
}
void print(int value)
{
std::cout << "Printing int: " << value << '\n';
}
void callme()
{
std::cout << "Called base class function" << '\n';
}
};
class Derived : public Base
{
int m_derived{};
public:
Derived(int value = 10, int base_value = 5)
: m_derived{value}, Base{base_value}
{
std::cout << "Creating derived" << '\n';
}
void identify()
{
std::cout << "From derived class" << '\n';
}
using Base::print;
void print(double value)
{
std::cout << "Printing double: " << value << '\n';
}
void callme()
{
std::cout << "Called derived class function" << '\n';
}
};
int main(int argc, char const *argv[])
{
Base base;
Derived derived;
derived.callme();
base.callme();
return 0;
}It prints:
Creating base
Creating base
Creating derived
Called derived class function
Called base class function
Now if we override the member function in derived class but we want to call base class function in the overridden function. For example:
#include <iostream>
class Base
{
int m_base{};
public:
Base(int value = 5)
: m_base{value}
{
std::cout << "Creating base" << '\n';
}
void identify()
{
std::cout << "From base class" << '\n';
}
void print(int value)
{
std::cout << "Printing int: " << value << '\n';
}
void callme()
{
std::cout << "Called base class function" << '\n';
}
};
class Derived : public Base
{
int m_derived{};
public:
Derived(int value = 10, int base_value = 5)
: m_derived{value}, Base{base_value}
{
std::cout << "Creating derived" << '\n';
}
void identify()
{
std::cout << "From derived class" << '\n';
}
using Base::print;
void print(double value)
{
std::cout << "Printing double: " << value << '\n';
}
void callme()
{
std::cout << "Called derived class function" << '\n';
Base::callme();
}
};
int main(int argc, char const *argv[])
{
Base base;
Derived derived;
derived.callme();
return 0;
}We can use Base::callme() to call base class member function.
However, if the function is a friend function, then we can use Base:: because it does not belong to the class. We then can use cast operator static_cast to cast derived object to base object as shown below:
#include <iostream>
class Base
{
int m_base_value{10};
public:
friend std::ostream &operator<<(std::ostream &out, const Base &b)
{
return out << "From base: " << b.m_base_value << '\n';
}
};
class Derived : public Base
{
int m_derived_value{10};
public:
friend std::ostream &operator<<(std::ostream &out, const Derived &b)
{
out << static_cast<const Base &>(b);
out << "From derived: " << b.m_derived_value << '\n';
return out;
}
};
int main(int argc, char const *argv[])
{
Base b;
std::cout << b << '\n';
Derived d;
std::cout << d << '\n';
return 0;
}