hey,

I've two classes and one class inherit the first class. I'm trying to add objects to vector (could be parent or child) and then call the overriding function (print) to display values passed in their respective constructors. But for some reasons only parent class' function (print) is invoked. I can't pinpoint the problem so I would appreciate if someone can help me, thanking in advance! I'm sharing my code:

example.h

class parent
{
public:
	char type;
	parent (char vType); 	
	virtual void print();
	virtual ~parent();  
 };

class child : public parent
{
public:
	string value; 
	child (char vType, string val); 
	void print();
};

example.cpp

#include <iostream>
#include <string>
using namespace std;
#include "example.h"

parent::parent(char vType) {
	parent::type = vType;
}

void parent::print() {
	cout << parent::type << endl;
}

parent::~parent() { }

child::child (char vType, string val):parent(vType) {
	child::value = val;
}

void child::print() {
	cout << child::type << ":" << child::value << endl;
}

main.cpp

#include <iostream>
#include <string>
using namespace std;
#include "example.h"

int main() {

       vector <parent> a;	
	a.push_back(parent('{'));
	a.push_back(child('x', "test");
	
	for (int i = 0; i < a.size(); i++) {
		parent * p = &a.at(i);
		p->print();
	}
	return 0;
}

Keep in mind that your vector stores parent objects, and when you
push_back (or add) a child object to the vector, you're assigning
the members that a parent object would know about to some copy that is stored in the vector.

To get the polymorphic behavior that you want, consider changing your vector so it holds pointers to parent types--

include <iostream>
#include <string>
#include <vector>

using namespace std;
#include "example.h"

int main() {

    vector <parent*> a;
    parent h('{');
    child c('x', "test");
    a.push_back(&h);
    a.push_back(&c);

    for (int i = 0; i < a.size(); i++) {
        parent * p = a.at(i);
        p->print();
    }

    return 0;
}

^Yes, it was the pointer mistake I was making; thanks for your help but I figured out the issue myself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.