-1

I have to do polymorphism for the go() function but i cant figure out how to access private variable distance. The complier keeps showing that

‘int Transport::distance’ is private within this context 5 | distance = 100;

Here is my code

Transport.h

#ifndef TRANSPORT_H
#define TRANSPORT_H
#include <iostream>
using namespace std;

class Transport{
    private:
        int distance;
    public:
        int get_dist_travelled();
        virtual void go();

};

#endif

Transport.cpp

#include "Transport.h"

        int Transport::get_dist_travelled(){
            return distance;
        }

Horse.h

#ifndef HORSE_H
#define HORSE_H

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

class Horse:public Transport{
    public:
        void go();
};

#endif

Horse.cpp

#include "Horse.h"
#include "Transport.h"

void Horse::go() {
     distance = 100;
}

main.cpp

#include <iostream>
#include "Transport.h"
#include  "Horse.h"
using namespace std;

int main(){
    Horse kid;
    kid.go();
    cout<<kid.get_dist_travelled()<<endl;

}
Alzain
  • 17
  • 5
  • 2
    You cannot. On the other hand, if it was `protected`... – Yksisarvinen Jun 17 '21 at 11:05
  • 1
    That's what `private` does. It makes the variable inaccessible (even to derived classes). Maybe you want `protected`, instead? – Adrian Mole Jun 17 '21 at 11:06
  • 1
    https://stackoverflow.com/questions/224966/what-is-the-difference-between-private-and-protected-members-of-c-classes – moooeeeep Jun 17 '21 at 11:10
  • 1
    In `Transport.h`, it has `#include ` but does not use it. Include what you use. Don't include what you don't use. It also has `using namespace std;` which is Very Bad™, and even more so in a header file. – Eljay Jun 17 '21 at 11:12
  • i changed it to protected – Alzain Jun 17 '21 at 11:15
  • @Eljay thank you i m aware of this but i still dont know which one i need to put std:: in front of – Alzain Jun 17 '21 at 11:16
  • You can't, at least not directly. Two options are to (1) make the `distance` member `protected` or `public` or (2) call the inherited `get_dist_travelled()` - which is already `public` and directly accesses the `distance` member (since it is a member function of the base class). I would prefer the latter - it achieves the required effect (obtaining (a copy of) the value of `distance` from the base class) and doesn't require changing the base class at all. If you need to change the value of `distance`, add a `protected` or `public` member of the base class that can change it. – Peter Jun 17 '21 at 13:06

1 Answers1

1

You can on the one hand make the variable protected, or define the class as a friend class.

tr1
  • 94
  • 3