-3

I'm trying to print out structs that I have made inside a function, and since these must be available outside of the function I have used pointers. I have declared the struct and functions like this in the header file:

struct Car{
double wheelDiam;
int numberOfWheels;
string brand;
};

void makeCars();

ostream & operator<<( ostream & out, const Car & elem );
void printCar( Car car);

The function that makes the cars looks like this:

void  makeCars(){
    Car *AstonMartin;
    Car *Volvo;
    Car *Audi;
    Audi->numberOfWheels = 4;
    Audi->wheelDiam = 20.0;
    Audi->brand = "Audi";
    Volvo->numberOfWheels = 4;
    Volvo->wheelDiam = 23.0;
    Volvo->brand = "Volvo";
    AstonMartin->numberOfWheels = 5;
    AstonMartin->wheelDiam = 25.0;
    AstonMartin->brand = "Aston Martin";

}

and I have made another function that prints out the struct (overloaded operator=):

ostream & operator<<( ostream & out, const Car & elem ){
    out << elem.brand<<"  "<<elem.numberOfWheels <<"   "<<elem.wheelDiam<<endl;
    return out;
}

void printCar( Car car){
    cout << car << endl;
}

but when I call the functions in main() it doesn't print anything and I get an error message:

int main(){
 makeCars();
 printCar(*AstonMartin);
return 0
}

whats the correct way to do this?

  • 1
    I think you need to refresh some of the basics. First of all, AstonMartin is a local variable to the makeCars() function, it is not available in main. Secondly, you are not creating any objects: `Car* AstonMartin` just declares a pointer but doesn't actually make a `new Car`. Finally, even if you did, you would still need to delete the objects – CompuChip Apr 14 '17 at 12:29
  • You should pick a good one from [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Apr 14 '17 at 12:45

1 Answers1

0

first of all, you declare the variable Car * AstonMartin in a function. This variable actually exists ONLY in the makeCars function.

you can't use your object or even delete it

a better way to do is

void setCarAttributes(Car *c)
{
   // set everything for you car
   c->setBrand("Aston Martin");
   // etc ...
}

void printCar()
{
   // print what you want

  }

int main()
{
    Car *AstonMartin = new Car();
    setCarAttributes(AstonMartin);
    printCar(AstomMartin);
}

nevermind the variable you declare in your functions can't be used in other functions. To use a variable everywhere you need to declare a global variable but in this case it's not necessary just declare a Car * and give it as parameter to your functions

RomMer
  • 909
  • 1
  • 8
  • 19