Gaetan
Gaetan

Reputation: 607

Access function f of class A in class B, while f need to access member variable of B

consider the following code:

class Car 
{
public:
  bool openCar();
}

class LocomotiveEngineer
{
public: 
   bool carRepair();

private:
   std::list<int> m_screwdriver;  
   std::vector<int> m_keys; 
   Car myCar; 
}

int main() {
    LocomotiveEngineer peter;
}

What I'm trying to solve is to allow the implementations of carRepair() and openCar() to fulfill the following 2 conditions:

That means in the cpp of LocomotiveEngineer I want to do something likes:

LocomotiveEngineer::carRepair() 
{
  openCar();     //carRepair() calls openCar()
}

and in the cpp of Car I have something likes:

Car::openCar()
{
   m_keys.size();             //openCar() can access m_keys via an instance of LocomotiveEngineer or whatever
   m_screwdriver.empty();   //openCar() can access m_screwdriver via an instance of LocomotiveEngineer or whatever
}

How can I design that? I'm constangly getting errors. I think I muss use things like: class forward declaration, friend, etc Thanks in advance. ps: I'm limited to c++11

Upvotes: 3

Views: 98

Answers (1)

Korni
Korni

Reputation: 464

just add the car as friend to the LocomotiveEngineer class:

class LocomotiveEngineer
{
public: 
    bool carRepair();

private:
   std::list<int> m_screwdriver;  
   std::vector<int> m_keys;

friend class Car;
}

But then you have to have an instance of an Lokomotive Engineer of course or declare the Engineers variables as static;

If you want to further specify the friend keyword, you can also only friend a specific function and not the whole class with friend bool Car::openCar(); instead of friend class Car;

Working Example

Header:

#include <vector>
class LocomotiveEngineer; // forward declare

class Car 
{
public:
  bool openCar(LocomotiveEngineer& repairmen); 
}

class LocomotiveEngineer
{
public: 
   bool carRepair(Car& broken_car); //specify the car whcih needs to be repaired

private:
   std::list<int> m_screwdriver;  
   std::vector<int> m_keys;

friend class Car;
}

cpp:

bool  LocomotiveEngineer::carRepair(Car& broken_car) 
{
  broken_car.openCar(*this);
  return true;
}

bool  Car::openCar(LocomotiveEngineer& repairmen){
    repairmen.m_keys.size();             //openCar() can access m_keys
    repairmen.m_screwdriver.empty();   //openCar() can access m_screwdriver
    return true;
}

main*

int main(){
    Car brokenCar;
    LocomotiveEngineer bob;

    bob.carRepair(brokenCar);

    return EXIT_SUCCESS;
}

I have to note, this way to do the job is not a good design, but sufficient for the beginning

Upvotes: 1

Related Questions