1

I understand how to create an object and i understand how to then create a pointer to that object. But I'm struggling to create a pointer to an object within another object/class.

I have created a Car and an Engine class. I want to have the Car class to have a pointer to an engine object that will be passed into the Car class's constructor. I am having no luck trying to figure out the correct syntax to do this.

Engine.h

#pragma once
class Engine
{

private:
    int _power;

public:
    Engine(int);
    ~Engine();

    int getPower();
    void setPower(int);
};

Engine.cpp

#include "stdafx.h"
#include "Engine.h"


Engine::Engine(int power)
{
    _power = power;
}


Engine::~Engine()
{
}

int Engine::getPower()
{
    return _power;
}

void Engine::setPower(int power)
{
    _power = power;
}

Car.h

#pragma once
#include "Engine.h"

class Car
{
private:
    Engine* _engine;
public:
    Car();
    ~Car();
}; 

Car.cpp

#include "stdafx.h"
#include "Car.h"


Car::Car(Engine &engine)
{
    _engine = engine;
}

Car::~Car()
{
}

Could someone please show me how I would go about this?

amdixon
  • 3,814
  • 8
  • 25
  • 34

1 Answers1

1

Simply change in Car.cpp

Car::Car(Engine &engine){...}

to

Car::Car(Engine* engine): _engine(engine){}

and also don't forget to change the signature of the constructor in Car.h to

Car(Engine*);

Otherwise you are mixing pointers with references, which are not semantically the same. Also consider using constructor initializer lists instead of assignments inside the constructor. For PODs it makes no difference, but for expensive-to-construct objects it makes a difference, since first the object is default-constructed, then assigned to it via a copy constructor.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • Thank you! Do you have any resources that explains the syntax use for the constructor? I have to implement this on a slightly larger scale, a better understanding might help avoid any more issues. –  Oct 05 '15 at 03:03
  • See e.g. http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/ Then take a look [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – vsoftco Oct 05 '15 at 03:05