William Capon William Capon - 19 days ago 5
C++ Question

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");
}

Answer

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/