Home > Software design >  How to keep a reference to a class on another?
How to keep a reference to a class on another?

Time:08-22

class cars
{
public:
   int price(int x);
}

class colors
{
public:
   int func1;
   int func2;
   cars fusca; // <---- error 'unknown override specified'
}

int colors::func1(...)
{
    //cars fusca;
    //this->cars = cars;  // <-- ???
}

int colors::func2(..)
{
   this->fusca.price(10);
}

How do I "define" an instance of cars inside of the class colors in which I could use in any other colors::... function?

If I declare cars fusca inside of colors i get this error: 'unknown override specified'

CodePudding user response:

I would keep a vector of smart pointers, like in the example below.

Keeping references is too dangerous as you have to control lifetimes very tightly (if that is what you meant by "reference").

#include <vector>
#include <memory>

class car
{
public:
   int price(int x);
};

class colors
{
public:
   void func1();
   void func2();
   using car_ptr = std::shared_ptr<car>;
   using car_vector = std::vector<car_ptr>;
   car_vector cars; 
};

void colors::func1()
{
    car_vector cars;
    this->cars = cars;  
}

void colors::func2()
{
    for ( car_ptr car : cars ) {
        car->price(10);
    }
}

Compiler explorer link

CodePudding user response:

Here a corrected version of your code, which would compile but not run:

class cars
{
public:
    int price(int x); // declared but not defined
}; // semicolon was missing

class colors
{
public:
   int func1(); // parenthesis was missing (member variable vs member function)
   int func2(); // parenthesis was missing (member variable vs member function)
   cars fusca; // this is actually not an error
}; // semicolon was missing

int colors::func1(/*...*/) // those 3 dots, why?
{
    //cars fusca; // this is ok, but has nothing to do with this->fusca
                  // local (blockscope) var vs member var
    //this->cars = cars; // class colors has no member cars,
                         // even if, you cannot assign a type to a member variable,
                         // but this->fusca = cars() would be ok
}

int colors::func2(/*..*/) // those 2 dots, why?
{
   this->fusca.price(10); // no problem here either (still not defined though)
}
  •  Tags:  
  • c
  • Related