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?