0
I’m having a problem involving inheritance in C++, I can’t change an attribute of a base class ex:
// classe base class Base { vector(string) Names; //coloquei entre parenteses porque por algum motivo o string desaparece quando coloco da maneira correta public: void Add(string); string Get(int); }; void Base::Add(string name) { this->Names.push_back(name); } string Base::Get(int name_position) { return this->Names[name_position]; } // classe derivada class void Derived : public Base { public: void New(string); }; void Derived::New(string name) { Base::Add(name); }
What I’m doing on Main is like this
Base base; Derived derived; derived.New("joao");
cout<<base.Get(0);
Can anyone tell me what I am doing wrong, I thought it was possible to change the attribute of a base class using the methods of the base class itself.
In the vector<string> Names I had put in parentheses because the stackoverflow editor was deleting the word <string>. No class void Derived : public Base was a typo and did not include the libraries because I only put the example snippet. But still it was not what I wanted, I wondered if it is not possible to call the get method of the base and it return me the value, maybe I am a little confused with the use of inheritance, I will study more.
– game doido
@gamemaluco The example you had are 2 different objects. You can’t put the value in one object and try to get it in another. The idea of inheritance is that an object has the fields and methods of the base class and the fields and methods of the derived class. Still, it’s all about the same object. In these cases it is common to have derived class methods that access base class methods/fields (referring to the same object) as you have in your example. The value you get in
derived.Get(0)
comes in the class truthBase
because that is where the array of names has been defined– Isac
Got it, thanks @Isac
– game doido
@gamemaluco No problem. I’m glad it made sense.
– Isac