Calling methods of actual object instead of parent class - c++

I have the following dummy code:
#include <iostream>
#include <vector>
using namespace std;
class Parent {
public:
void printHello() {
cout << "Hello Parent" << endl;
}
};
class Child : public Parent {
public:
void printHello() {
cout << "Hello Child" << endl;
}
};
int main() {
vector<Parent*> list;
Child child;
list.push_back(&child);
list[0]->printHello();
}
Output: Hello Parent
I am trying to create a list of objects of classes derived from the parent class. Iterating over them and running a method they all inherit and override.
I had assumed the method in the child class would have overridden the method in the parent class.
I have also tried the approach of using vector<Parent> instead of vector<Parent*>.
The result has been the same. How can I call the methods of the derived classes instead of the parent class?

Use virtual methods - http://en.cppreference.com/w/cpp/language/virtual. Read more about them here.
#include <iostream>
#include <vector>
class Parent {
public:
// using virtual keyword
virtual ~Parent() = default;
virtual void printHello() const { std::cout << "Hello Parent" << std::endl; }
};
class Child : public Parent {
public:
// using override keyword though its not necessary
void printHello() const override { std::cout << "Hello Child" << std::endl; }
};
int main()
{
std::vector<Parent *> list;
Child child;
list.push_back(&child);
list[0]->printHello();
}
Output -
Hello Child

In C++ you have to use virtual in the parent class method definition to specify that you are going to use a polymophic method. The default behavior in C++ is not polymorfic.
#include <iostream>
#include <vector>
using namespace std;
class Parent {
public:
virtual void printHello() {
cout << "Hello Parent" << endl;
}
};
class Child : public Parent {
public:
void printHello() {
cout << "Hello Child" << endl;
}
};
Check this out for more info: Polymorphism in C++

To get the behavior you want, that method needs to be declared virtual in the parent class. See http://en.cppreference.com/w/cpp/language/virtual for more information.

Related

why is the child function not getting called while inheriting a singleton in c++

I have the following test code. Here, the output is "from parent", how can I call the child function? Why is the child function not getting called? is is recommended to inherit from a singleton?
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton& getInstance()
{
static Singleton s;
return s;
}
virtual void func()
{
cout << "from parent" << endl;
}
};
class Child : public Singleton
{
public:
void func() override
{
cout << "from child" << endl;
}
};
int main()
{
Singleton& s = Child::getInstance();
s.func();
}
Right now, Singleton::getInstance always returns a Singleton. Child doesn't have its own version of getInstance, so Child::getInstance() resolves to a call to Singleton::getInstance() which returns a Singleton, not a Child. If we use the CRTP, we can make it so Singleton::getInstance actually knows the derived type we're trying to get an instance of:
#include <iostream>
#include <type_traits>
template <class Derived>
class Singleton
{
public:
static Derived& getInstance()
{
// Assert that the template arg really is derived from the appropriate instantiation of the base class template
static_assert(std::is_base_of<Singleton<Derived>, Derived>::value);
static Derived s;
return s;
}
virtual void func()
{
std::cout << "from parent" << std::endl;
}
};
class Child : public Singleton<Child>
{
public:
void func() override
{
std::cout << "from child" << std::endl;
}
};
int main()
{
auto& s = Child::getInstance(); // s is a Child here
s.func(); // Outputs "from child" as expected
}

Call function of child in parent pointer vector

I am trying to make a vector of Child and Parent objects. I have a function foo() in Child class which overrides foo() in Parent, and prints No instead of Yes. However, when I call the foo() function of all objects in the vector the parent foo() function is run for the child object. Is there a way to have all children objects in the vector to run the overridden function while parent objects run the parent function?
To extend the question can that also be done for multiple classes which extend the Parent class and override the foo() function.
Here is the code:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Parent {
public:
Parent () {
cout << "New Parent" << endl;
}
void foo() {
cout << "Yes" << endl;
}
};
class Child : public Parent {
public:
Child(): Parent() {
cout << "New Child" << endl;
}
void foo() {
cout << "No" << endl;
}
};
int main()
{
vector<std::unique_ptr<Parent>> v;
v.push_back(std::make_unique<Parent>());
v.push_back(std::make_unique<Child>());
for (auto i = v.begin(); i != v.end(); ++i){
(*i)->foo();
}
return 0;
}
The output is:
New Parent
New Parent
New Child
Yes
Yes
The output i would like is:
New Parent
New Parent
New Child
Yes
No
foo() needs to be declared as virtual in Parent in order for Child (and other descendants) to override it.
Parent should also have a virtual destructor, as well, so that descendant destructors are called correctly when delete is called on a Parent* pointer (such as by std::unique_ptr<Parent>).
Try this:
class Parent {
public:
Parent () {
cout << "New Parent" << endl;
}
virtual ~Parent () {}
virtual void foo() {
cout << "Yes" << endl;
}
};

Inheritance and Changing Variables in C++

I'm making an inventory system, and am trying to use derivatives to create different items, so that I can have default elements in the parent and specialized ones in the children.
So what I've written below, at the moment it prints "I'm a parent" but I am trying to get it to print "I'm a kid", and in the lack of a child definition of stuffToSay print "I'm a parent" Thanks!
using namespace std;
class myParent {
public:
virtual void saySomething() {
cout << stuffToSay;
}
string stuffToSay = "I'm a parent";
private:
};
class myDerivitive : public myParent{
public:
myDerivitive() {};
string stuffToSay = "I'm a kid";
private:
};
int main() {
myParent* people[] = {
new myDerivitive()
};
cout << people[0]->stuffToSay;
system("pause");
}
Thats not how it works. The saySomething in parent doesn't know anything about the string in the derived class and member variables aren't virtual.
You can do it e.g. like this
#include <iostream>
#include <string>
struct myParent {
void saySomething() {
cout << getSomething();
}
virtual std::string getSomething(){ return "I'm a parent"; }
virtual ~myParent(){} // virtual destructor is needed
};
struct myDerived : myParent {
virtual std::string getSomething(){ return "I'm the derived"; }
};
int main() {
myParent* p = new myDerived();
p->saySomething();
delete p; // dont forget to delete !!
}
Something like this is normally done using the constructor of your class, the child class has all the variables of its parent class so to do what you are looking for it can be done like this:
using namespace std;
class myParent {
public:
myParent() {
stuffToSay = "I'm a parent"
}
virtual void saySomething() {
cout << stuffToSay;
}
string stuffToSay;
private:
};
class myDerivitive : public myParent{
public:
myDerivitive() {
stuffToSay = "I'm a kid";
};
private:
};
int main() {
myParent* people = new myDerivitive();
cout << people->stuffToSay();
delete people; // Simplified to a single pointer and remember to delete it
people = NULL;
system("pause");
}
Please take a look at this link for more information on classes:
http://www.cplusplus.com/doc/tutorial/classes/
This link will help with the understanding of inheritance, since your derivative class would have the "stuffToSay" variable since its parent had it:
http://www.cplusplus.com/doc/tutorial/inheritance/
There is no such thing as a virtual or overridden variable in C++; that sort of polymorphism only applies to methods. So you could do this:
struct parent {
virtual void saySomething() {
cout << "I'm a parent!\n";
}
};
struct child: parent {
void saySomething() override {
cout << "I'm a child!\n";
}
};
Or you could solve it with something more like your current structure by adding a layer of indirection:
struct parent {
void saySomething() {
cout << thingToSay() << '\n';
}
private:
virtual string thingToSay() { return "I'm a parent!"; }
};
class child: parent {
virtual string thingToSay() { return "I'm a child!"; }
};

C++ override inherited methods

I have the following two classes. Since Child inherits from Father, I think that Child::init() overrides Father::init(). Why, when I run the program, I get "I'm the Father" and not "I'm the Child"? How to execute Child::init()?
You can test it here: https://ideone.com/6jFCRm
#include <iostream>
using namespace std;
class Father {
public:
void start () {
this->init();
};
void init () {
cout << "I'm the father" << endl;
};
};
class Child: public Father {
void init () {
cout << "I'm the child" << endl;
};
};
int main (int argc, char** argv) {
Child child;
child.start();
}
Currently Child::init is hiding Father::init, not overriding it. Your init member function needs to be virtual in order to get dynamic dispatch:
virtual void init () {
cout << "I'm the father" << endl;
};
Optionally, you could mark Child::init as override to be explicit that you want to override a virtual function (requires C++11):
void init () override {
cout << "I'm the child" << endl;
};
You should define the function with function specifier virtual
For example
#include <iostream>
using namespace std;
class Father {
public:
virtual ~Father() {}
void start () {
this->init();
};
virtual void init () const {
cout << "I'm the father" << endl;
};
};
class Child: public Father {
void init () const override {
cout << "I'm the child" << endl;
};
};
int main()
{
Child child;
child.start();
return 0;
}
Otherwise function start searches name init in the scope of its own class. And because function init is not virtual that is it is not overriden in the derived class the base class function init is called.
If you want the child to override the init method, you must make the init method in the base class virtual.
class Father {
public:
void start () {
this->init();
};
virtual void init () {
cout << "I'm the father" << endl;
};
};
A class that re-declares and re-implements a virtual method of one of its bases, is said to override that method. In order for late binding to occur for a method, you need to declare that method virtual.

How can a subclass call a method of the superclass with the same method name of the subclass?

#include <iostream>
using namespace std;
class Person {
public:
void sing();
};
class Child : public Person {
public:
void sing();
};
Person::sing() {
cout << "Raindrops keep falling on my head..." << endl;
}
Child::sing() {
cout << "London bridge is falling down..." << endl;
}
int main() {
Child suzie;
suzie.sing(); // I want to know how I can call the Person's method of sing here!
return 0;
}
suzie.Person::sing();
The child can use Person::sign().
See http://bobobobo.wordpress.com/2009/05/20/equivalent-of-keyword-base-in-c/ for a good explanation.