Change an attribute of a base class by the C ++ derived class

0

I have a problem involving inheritance in C ++, I can not change an attribute of a base class eg:

// 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 in main is like this

  
Base base;
Derived derived;
derived.New("joao"); 
cout<<base.Get(0);

Can anyone tell me what I'm doing wrong, I thought it was possible to change the attribute of a base class using the methods of the base class itself.

    
asked by anonymous 23.01.2018 / 21:28

1 answer

1

You have some errors in your code:

  • vector(string) Names; must be vector<string> Names; .

    In order for it to work, you have to import its libraries:

    #include <vector>
    #include <string>
    

    And put using namespace std or transform each one into std::vector and std::string

  • class void Derived : public Base stayed with the reserved word void more and should become:

    class Derived : public Base
    
  • cout<<base.Get(0); What I wanted to do actually was cout<<derived.get(0) . Notice that your main has created two instances:

    Base base;
    Derived derived;
    

    And then assigns the name through the instance named derived :

    derived.New("joao"); 
    

    This instacia is of type Derived which is derived from Base and therefore has vector<Names> inherited. It is in this instance that you have to use the Get method that goes to the inherited vector to find the name:

    cout<<derived.Get(0);
    

Your complete code with these fixes would be:

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

class Base{
    std::vector<std::string> Names;
    public:
        void Add(std::string);
        std::string Get(int);
};
void Base::Add(std::string name){
    this->Names.push_back(name);
}
std::string Base::Get(int name_position){
    return this->Names[name_position];
}
// classe derivada
class Derived : public Base{
    public:
        void New(std::string);
};
void Derived::New(std::string name){
    Base::Add(name);
}

int main(){
    Derived derived;
    derived.New("joao");
    std::cout<<derived.Get(0);

    return 0;
}

See Ideone on how to display the correct result

    
23.01.2018 / 23:54