Constructors and Copy Constructors accross Identical derived classes - c++

Is it possible to use a copy constructor to initialize an identical derived class from that derived classes "twin"?
I mean I want to initialise an object of type Computer that is identical to an object I already initialised of type User.
Computer cCarrier = User uCarrier; Kind of thing.
E.g
class Game
{
public:
//No constructor Intentional
protected:
int m_iSize;
string m_strName;
};
class User: public Game
{
public:
User(int _iSize, string str_Name);
~User();
};
class Computer: public Game
public:
Computer(int _iSize, string str_Name);
~Computer();
};
main.cpp
#include "game.h"
using namespace std;
int main()
{
User carrier(5, "Airship Carrier");
//Computer carrier = User::carrier;
};
They are identical derived classes, I have only made them this way as a virtual and visual way to represent the User and AI battleships in the programming code, for the programmer, and for testing a sides ships for collisions against each other and firing shots.

Well either you want 2 different types and then you cannot do that ( cannot create a Cat from a Dog), or you want them to share the same type but to be manipulated thru different typenames then you should just use a typedef:
class Game
{
public:
Game(int _iSize, string str_Name);
private:
int m_iSize;
string m_strName;
};
using User = Game;
using Computer = Game;
Nevertheless, from a design standpoint, this way of doing it seem incorrect as a Computer is not a User (IMHO).
On another hand, you could create a constructor in user and in Computer that builds from a Game; something like:
class Computer {
Computer(const Game &game) : Game(game) { /*...*/ }
/*...*/
};
but remains the fact that building a User from a Computer seems "strange".

The only relationship between your User and Computer types is that they both derive from Game.
As such, there is no way to implement a constructor of either by delegating to the other in the way you want (short of containment, which is creating distinct objects, not using the constructor of one type to initialise an instance of an unrelated type).

User and Computer are different type at all. You can add a template copy constructor for it.
Add getter in the base class:
class Game
{
public:
//No constructor Intentional
int get_iSize() { return m_iSize; }
string get_strName() { return m_strName; }
protected:
int m_iSize;
string m_strName;
};
then
class Computer: public Game
{
public:
template <typename T>
Computer(const T& t) {
m_iSize = t.get_iSize();
m_strName = t.get_strName();
}
// ...
};
And consider to make the constructor explicit to avoid unexpected implicit casting.

Related

Macros for creating named constructors

I am trying to play with c++ and macros for the first time. SO basically in a lecture I know where a coded value is used to distinguish different modes of an object (game_type in this case), then these objects must be created via constructors with meaningful named constructors. SO I created createSinglePlayerGame() and named constructors. Then I tried to optimize this code using macros. SO In the Game class I define the function- like macro consructor A ## operator which runs parameter replacement on the two identifiers and then concatenates the result ("token pasting).
Can you look at my code and suggest a better way of doing this, also do you see any hygiene problem that my macros may be used incorrectly,
class Game
{
public:
#define CONSTRUCTOR(name, a) static Game create_##name() { return Game(a);}
CONSTRUCTOR(Single, 0)
CONSTRUCTOR(Multiple, 2)
// named constructors
static Game createSinglePlayerGame() { return Game(0); }
static Game createMultiPlayerGame() { return Game(1); }
protected:
Game(int game_type);
};
int main()
{
Game myGame = Game::createSinglePlayerGame();
Game second = Game::create_Single();
}
A more conventional way would be:
enum class GameType {
SinglePlayer,
MultiPlayer,
};
class Game
{
public:
explicit Game(GameType type);
};
int main()
{
Game myGame(GameType::SinglePlayer);
}
This is simpler and will be less surprising for other C++ developers to read. It's also less error-prone: even your example code confuses 1 and 2 for multiplayer mode, and since you use raw integers to store it, there's no complaint from the compiler. Using enum class it will be much harder to make such mistakes.
As an alternative to John Zwincks solution, you can also use inheritance:
class Game {
protected:
Game(int game_type);
};
class SinglePlayerGame: public Game {
public:
SinglePlayerGame(): Game(0) {}
};
class MultiPlayerGame: public Game {
public:
MultiPlayerGame(): Game(1) {}
};
int main() {
SinglePlayerGame myGame;
...
}
Although I would only use this method if there were more differences in the interface between single- and multiplayer games than just the constructor.
If you want an alternative to macros you can also use templates. Templates is something that compiler "understand" and optimize.
Their syntax may be confusing at start but if you play with them you can get used to it...
// Tag types for template dispatching
struct SinglePlayer {};
struct MultiPlayer {};
// Default single player
template <typename G>
class Game {
public:
Game () { /* create default single player game */ }
};
// Specialization for multi player
template <>
class Game <MultiPlayer> {
public:
Game () { /* create multiplayer player game */}
};
int main (void) {
Game g1 = Game<SinglePlayer>();
Game g2 = Game<MultiPlayer>();
}
This approach split the class definition into 2. One for single player and one for multi player. If they share a lot of common staff and you believe that this should not be the case, you may consider to avoid the class template and use std::enable_if<> in the constructor's level.
For example:
#include <type_traits>
// Tag types for template dispatching
struct SinglePlayer{};
struct MultiPlayer{};
struct Game {
public:
template <
typename G,
std::enable_if_t<std::is_same<G, SinglePlayer>::value, int> = 0
>
Game(G) { /* create a single player game */ }
template <
typename G,
std::enable_if_t<std::is_same<G, MultiPlayer>::value, int> = 0
>
Game(G) { /* create a multi player game */ }
};
int main (void) {
Game g1 = Game(SinglePlayer{});
Game g2 = Game(MultiPlayer{});
}
Notice that there is no class template any more, only a SFINAE dispatch for the constructors. The disadvantage is the dummy pass of a SinglePlayer{} or MultiPlayer{} object to the constructor.

C++: Extend member type in derived class

I'd welcome some help with C++ inheritance to get a better grasp of the concept.
Is it possible to "extend" member types when creating a derived class? I think my problem can be best demonstrated by a simple example, where I'd like to extend the class VehicleData with a new double variable:
class VehicleData {
int yearOfManufacture;
//Different routines, for example Serialize(), etc., warranting to create a class for just a bunch of variables
};
class BicycleData:VehicleData {
double frameHeight; //new property that only applies to bicycles
};
//Now I create the actual classes that use the types above
class Vehicle {
VehicleData data;
void PrintData(); //a function that works on basic vehicle data
};
class Bicycle:Vehicle {
BicycleData data; //should copy VehicleData when creating an instance of this class
};
The problem with this approach is that when I code the above and create a Bicycle instance, its BicycleData member hides the already existing VehicleData member.
Is there a way to extend the base class, i.e. simply add a new double variable (to store frame height in this example), and keep the already existing (year of manufacture) data?
As far as I can tell, there is no clean way to do exactly what you want with inheritance alone.
You could create a template out of your base class:
template <typename Data>
class BaseVehicle
{
Data data;
// etc.
};
class Vehicle : BaseVehicle<VehicleData>
{
// etc.
};
class Bicycle : BaseVehicle<BicycleData>
{
// etc.
};
Then the Vehicle and Bicycle classes would contain data field of VehicleData and BicycleData types respectively.
Since in your example Bicycle inherits from Vehicle privately (i.e. there is no support for using Bicycle polymorphically via pointer/reference to Vehicle), this would effectively be identical to what you want to achieve.
If you do want dynamic polymorphism, you should create a separate, preferably abstract, class, defining the interface for your vehicles, e.g.:
class VehicleInterface
{
public:
// Some pure virtual interface methods
virtual void moveTo(const Vector2 position) = 0;
virtual ~VehicleInterface() = default;
};
And then you can have your concrete vehicles inherit and implement this interface:
class Vehicle : BaseVehicle<VehicleData>, public VehicleInterface
{
public:
virtual void moveTo(const Vector2 position) override
{
// implementation for Vehicle
}
};
class Bicycle : BaseVehicle<BicycleData>, public VehicleInterface
{
public:
virtual void moveTo(const Vector2 position) override
{
// implementation for Bicycle
}
};
Then any function, which would like to work with vehicles polymorphically, can just accept a reference or a pointer to VehicleInterface:
void driveToWork(VehicleInterface* vehicle)
{
vehicle->moveTo(getWorkPosition());
// etc.
}
Short answer; Not in the way that you're aiming for, but you can achieve something similar.
Rather than have an instance declared as you have, if you make data a pointer. You can then have BicycleData inherit VehicleData and then just replace data with the new instance in the constructor of the Bicycle.
ie
class Vehicle {
void PrintData();
protected:
void replaceData(std::shared_ptr<VehicleData> d) {
data = d;
}
std::shared_ptr<VehicleData> getData() {
return data;
}
template<class T>
std::shared_ptr<T> getDataAs() {
return std::dynamic_pointer_cast<T>(data);
}
private:
std::shared_ptr<VehicleData> data;
};
class Bicycle:Vehicle {
Bicycle(){replaceData(std::make_shared<BicycleData>());}
std::shared_ptr<BicycleData> getData() {
return getDataAs<BicycleData>();
}
};

C++ Creating Child Class from a Parent Class that's already been initialised

I have a class "Player". Its members are simple strings and ints and I've got Getters and Setters for each of these...basic stuff: (there's a load of members so I've just given 3 to shrink the code):
PLAYER.H
class Player
{
private:
string Name;
string Role;
int FFDefence;
......etc
public:
//constructor function
Player(
string Name = "Not Stated",
string vRole = "Not Stated",
int vFFDefence = 0,
......etc
)
//Getter Functions
string GetName() const;
string GetRole() const;
int GetFFDefence() const;
.....etc
//Setter Functions
void SetName (string x);
void SetRole(string x);
void SetFFDefence(int x);
......etc
};
PLAYER.CPP
Player::Player( string vName,
string vRole,
int vFFDefence,
......etc
{
Name = vName;
Role = vRole;
FFDefence = vFFDefence,
......etc
}
//getter functions
string Player::GetName() const {return Name; };
string Player::GetRole() const {return Role; };
int Player::GetFFDefence() const {return FFDefence; };
.....etc
//Setter Functions
void Player::SetName(string x) { Name = x ; };
void Player::SetRole(string x) { Role = x ; };
void Player::SetFFDefence(int x) { FFDefence = x ; };
......etc
So yeah - pretty bog standard......now I have a second class where one of the member functions is a Player Class itself.
BATTER.H
class Batter
{
private:
Player ID;
int Touch;
....etc
public:
Batter(Player vID, int vTouch = 0....etc);
//Getter Functions
string GetRole() const;
int GetFFDefence() const;
int GetBFDefence() const;....and so on.
OK - that's the code out of the way!!!!
So I've got it doing everything I want in terms of passing variables in and out....so I can create
Player Dave ("Dave", "Opener", 98, ....etc)
then later on (when I need it) create
Batter OnStrike (Dave, 10, .....etc)
All gravy....OK so I've started looking into inheritance and realized this is what I should be doing....back converting not a problem (did this with arrays and vectors the other day)...
Here's my problem:
With what I've got now, I can create "Player Dave" and then pass him into the subclass of Batter whenever I need to. How do I do the same with traditional inheritance? How do I take a specific instance (already created) of Player and use that as the parent for a specific instance of the child class Batter? As far as I can deduce at the moment, you need to create both at the same time.
Just initialize your base object with the object provided:
class Player
{
Player(Player const&); // copy constructor (might be implicitly generated)
...
};
class Batter:
public Player
{
Batter(Player const& p, other arguments):
Player(p),
...
{
...
}
};
On the other hand, there's the question whether inheritance of Batter from Player is the right tool in your case. The fact that you pass a Player object to construction hints at the fact that a Player may become a batter, and maybe later also stop being a batter. That is, Batter is actually a role which the player may temporarily have. Therefore it may be a better idea to separate the Player object from the role, by having a separate Role hierarchy where Batter and Pitcher derive from Role, and Player has a method which returns the current role, and another which can assign another role to the player.
The idea with polymorphism is that if you have some class:
class Batter : public Player
Then every batter is also a player. So, for example, if you had a batter called dave, you'd be able to use dave wherever a Player was expected. You could for example:
int FunctionThatDoesSomething(Player &p, string some_parameter, ...);
...
FunctionThatDoesSomething(dave, "foo", ...);
Be careful to avoid slicing, which is when you accidentally make a base class copy of a subclass (this does not preserve subclass specific state. If you need to pass dave around, make sure you only refer to dave, don't copy dave. dave doesn't like to be copied.)
How exactly you build your players and batters is up to you. For example, your might have constructors with these signatures:
Player::Player(string name, string role, int vFFDefense);
Batter::Batter(Player &p, int vTouch, int moreStats);
Under some circumstances this might be convenient, but it's not particularly efficient because you have to create and copy the base class (not that efficiency is a big deal for small classes like this, but there's no point in trying to do things the dumb way). You would be better off making a constructor that takes everything it needs, and uses subobject initialization:
Batter::Batter(string name, string role, int vFFDefense, int moreBaseStats, int vTouch, int moreStats) : Player(name, role, vFFDefense, moreBaseStats)
{
...
But your implementation is ultimately up to you.
You are doing aggregation here, not inheritance. A Batter has a player. Inheritance would be a batter is a player.
Your design is good, you don't want to do inheritance for this.
While it's okay to say a Batter is always a Player from a conceptual point of view in this case, when you are dealing with a Batter, much of what player describes is irrelevant and when dealing with them as a player, they may not be batting.
Baseball is a bit foreign to me, but if you went down the inheritance route, you'd have descendants of player for each role in the team and get in a right mess when your pitcher came out to bat.
A classic illustration of the inheritance route.
Is
Animal -> Fliers -> Bird -> Merlin
-> Runners -> Rodent -> Gerbil
Where do you put Bat and Ostrich?
You are left with saying a Bat is a bird, inventing a new class FlyingRodent, or Rodent having two parents...
All of which will lead to a confusing bug fest.
View all unconscious reaches for the inheritance hammer with extreme suspicion.
It really depends how you actually want your code factored.
Will a given Player ever become anything other than a Batter? If they can, then it is probably best to use aggregation (in a similar way to how you do now).
If you are aggregating then maybe use another class to hold the data. You could have a PlayerInfo class or struct and aggregate that:
struct PlayerInfo
{
string role_;
int ff_defence_;
...
};
class Player
{
public:
Player(PlayerInfo const& info)
: info_(info)
{}
virtual ~Player() = 0;
virtual void doSomething();
PlayerInfo const& getPlayerInfo() const { return info_; }
private:
PlayerInfo info_;
};
class Batter : public Player
{
public:
Batter(PlayerInfo const& info)
: Player(info)
{}
virtual void doSomething();
};
If you actually want the inheritance then other answers here tell you what you need to do - construct an instance of Batter and pass on the constructor arguments to a constructor of the class you derive from (e.g. Batter) to initialize it.
Think carefully about what are you trying to express in your code.
The reason you would want to have Batter derived from Player is if you need virtual functions in Player that are implemented in Batter and do something different depending upon whether or not it is a Player or a Batter.
As an aside, its best to keep base classes abstract if possible, so Player would never be instantiated directly and would always need to be derived. I'd recommend reading Scott Meyers 'More Effective C++' to understand why this is. There's a section in there devoted to that. In fact some of the finer points of inheritance and OO design in general are nicely explained.
What you may actually want is something slightly different depending upon where you anticipate your model to change, and additionally where you you need it to have the dynamic behaviour possible through the use of virtual functions?
You could have a Player class that has all your player specific details. Then you could have a PlayerBehaviour class that implements what the player does:
class Player;
class PlayerBehaviour
{
public:
virtual ~PlayerBehaviour() = 0;
virtual void doSomething(Player* player) = 0;
};
inline PlayerBehaviour::~PlayerBehaviour() {}
class BatterBehaviour : public PlayerBehaviour
{
public:
virtual void doSomething(Player* player) {
if (player->isAngry()) {
throwBatOnFloor();
}
}
void throwBatOnFloor();
};
class Player {
public:
Player(...stuff...);
void doSomething() {
if (behaviour_.get()) {
behaviour_->doSomething(this);
}
}
private:
auto_ptr<PlayerBehaviour> behaviour_;
// Due to the auto_ptr, the default copy and assignment operators are
// dangerous. You could use a smart pointer or implement
// these by having a clone() function in the behaviour class.
// Therefore copy/assign are private to prevent accidental misuse.
Player(Player const&);
Player& operator=(Player const&);
};
So, inheriting Batter from Player models the situation as a Batter is-a Player.
Having a Behaviour models the situation as a Player has-a Behaviour such as a Batter.
Stop using the "parent" and "child" terminology, think of "base" classes and "derived" classes ... that's what everyone else calls them. "Parent" and "child" can be used in too many other ways (e.g. an object that owns another one) so it's confusing terminology if you're talking about an inheritance relationship.
The derived class contains an entire instance of the base type inside itself. When the derived constructor starts executing the first thing it does is construct all its bases, which it does by calling their constructors. So the derived class can control how the base is constructed by passing it the right arguments:
class Base {
public:
Base(std::string nm) : name(nm) { }
protected:
std::string name;
};
class Derived : public Base {
public:
// construct my base by passing name to it
Derived(std::string name, int ii) : Base(name), i(ii) { }
private:
int i;
};
Derived d("Dave Derived", 1);
This creates both the Base and Derived objects at the same time (one inside the other) which is probably what you want.
If do have an existing Base object and you want the base part of the derived object to be the same as that other one then you can pass it an object to copy:
class Base {
public:
Base(std::string nm) : name(nm) { }
protected:
std::string name;
};
class Derived : public Base {
public:
// construct my base by passing name to it
Derived(std::string name, int ii) : Base(name), i(ii) { }
// construct my base by passing another Base to it:
Derived(const Base& b, int ii) : Base(b), i(ii) { }
private:
int i;
};
Base b("Barry Base");
Derived d(b, 2);
This doesn't put the existing Base object, b, inside the Derived one, instead it makes the base object a copy of the object b, by calling the Base copy constructor, so now there are two Base objects, the original b and the one inside d. This is closer to your original code, where the Batter contains a Player member, but now it's a base class not a member.
If you do want to use inheritance, the first form is probably more appropriate, where you pass arguments to the derived class and it uses those arguments to create the base.

Using C++ templates to create a class with custom components

Let me explain what I am asking for by an example. Imagine I have a class for a car.
Now, the car may have a lot of extras:
4 doors instead of only 2
Automatic door locking
4 Wheel drive
I want to create the class with any combination of these options. Any of these options needs some data members. Imagine the class now looks like this:
class Car {
public:
bool FourDoors;
bool AutomaticDoorLocking;
bool FourWheelDrive;
Door doors[4]; //4 only needed if FourDoors=true
DoorLockingElectronic doorElectronic; //Only needed if AutomaticDoorLocking=true
TransmissionsShafts[4]; //4 only needed for FourWheelDrive=true
void lockDoors() {
if (AutomaticDoorLocking) {
doorElectronic.lockDoors();
} else {
// Do manual door locking
}
}
};
So far so good, but now I want to create a lot of cars, so many that memory gets critical. And I do not need most of the extras in most of those cars.
I could create a base class, and derive classes with those options enabled or disabled.
But I would have to create 2^{#extras} classes to create all possible combinations, with a lot of double code.
So I thought maybe templates could be used? (that is the question).
I can imagine having a flag template, and rewrite the lockDoors like this:
template<int flags>
void Car<flags>::lockDoors() {
if (flags | AutomicDoorLockingFlag) {
doorElectronic.lockDoors();
} else {
// Do manual door locking
}
}
Wonderful! But the class Car<0> still takes a lot of unnecessary space. So:
Can I somehow include or exclude class members depending on a template parameter?
Other Ideas how to deal with the situation are also welcome!
You want to use policy classes:
class FourDoorPolicy { Door m_doors[4]; ... };
class TwoDoorPolicy { Door m_doors[2]; ... };
class AutoDoorLockingPolicy { ... };
class ManualDoorLockingPolicy { void lockDoors(); ... };
class FourWheelDrivePolicy { TransmissionShafts m_shafts[4]; ... };
class TwoWheelDrivePolicy { TransmissionShafts m_shafts[2]; ... };
template <class DoorPolicy = TwoDoorPolicy,
class LockingPolicy = ManualDoorLockingPolicy,
class DrivePolicy = TwoWheelDrivePolicy>
class Car : public DoorPolicy, public LockingPolicy, public DrivePolicy
{
...
};
Put all the policy specific stuff (e.g. lockDoors() function) inside the policy classes rather than the Car class. The Car class inherits these, which is a form of composition (i.e. you are building all their functionality into the Car class).
Note that you should give all the policy classes a protected, non-virtual destructor so that they can only be instantiated as part of a derived class.
You then instantiate customised cars in the normal template manner:
Car<FourDoorPolicy, AutoDoorLockingPolicy, TwoWheelDrivePolicy> myCar;
Of course, you can use typedefs to help with this (and template aliases in C++0x will help a lot, too).
See: Policy-based Design
You probably should look into Policy-based design. Basically, it consists as externalizing behaviors in policy classes and instantiating a template car object with the appropriate policies. A policy class is responsible for the encapsulation of a given behavior.
From an implementation point of view : Car becomes a template where each type argument corresponds to a given policy (for example : DoorLockingPolicy). Your car template can then be "configured" depending the types you choose to instantiate it with : ManualDoorLockingPolicy or AutomaticDoorLockingPolicy.
template<class DoorLockingPolicy /*, class DoorsPolicy, ... */>
class Car : DoorLockingPolicy
{
public:
void lockDoors()
{
/* ... */
DoorLockingPolicy::lockDoors();
}
};
struct ManualDoorLockingPolicy
{
void lockDoors() { /* ... */ }
};
struct AutomaticDoorLockingPolicy
{
void lockDoors() { /* ... */ }
};
int main()
{
Car<ManualDoorLockingPolicy> car1;
Car<AutomaticDoorLockingPolicy> car2;
}
From a performance point of view, policy-based design is a great way to achieve "don't pay for what you don't use" :
Calls to the policy classes can be inlined and introduce no additional cost
The Car template can inherit privately from its policies and benefit from the empty base optimization.
Once again, Modern C++ Design (Andrei Alexandrescu) is a great read on this topic.
The problem as I see it is that you're trying to define a single class which is capable of representing all possible version of a "Car", meaning that each instance contains member data capable of representing all possible cars. This problem was solved eons ago by traditional inheritance.
Define the functionality common to all cars in the base class. Then derive specific classes which add functionality (and member variables which increase the memory footprint). You minimize your memory simply by instantiating the proper sub class. Each instance contains only the members important to that specific type of Car.
One possibility would be to introduce a feature class. The feature class would have some kind of a unique identifier (I've used int for the hell of it, but boost::uuids::uuid would be more preferable). It does nothing but define a feature of some sort:
class Feature
{
private:
int m_nUniqueID;
protected:
Feature(int _uniqueID) : m_nUniqueID(_uniqueID) {};
virtual ~Feature(){};
public:
const int& getUniqueID const {return(m_nUniqueID);};
}; // eo class Feature
From this, we can derive more concrete features:
class DoorsFeature : public Feature
{
private:
int m_nDoors;
public:
static const int UniqueId;
DoorsFeature(int numDoors) : Feature(UniqueId), m_nDoors(numDoors){};
virtual ~DoorsFeature(){};
void lockDoors() { /* lock the doors */ };
}; // eo class DoorsFeature
class ABSFeature : public Feature
{
public:
static const int UniqueId;
ABSFeature() : Feature(UniqueId){};
virtual ~ABSFeature(){};
}; // eo class ABSFeature
And onwards for any kind of feature that the car can have. Note I would not class wheels as a feature because, well, all cars have wheels although the number may differ. I am referring to various traits that can differ wildly such as electronic doors, ABS, etceteras. Suddenly, your car becomes a much simpler container:
class Car
{
private:
int m_nWheels;
std::string m_Colour;
std::vector<Feature> m_Features;
protected:
public:
Car();
~Car();
void addFeature(Feature& _feature) {m_Features.push_back(_feature);};
Feature getFeature(int _featureId) const;
void lockDoors()
{
DoorsFeature& doorsFeature(static_cast<DoorsFeature&>(getFeature(DoorsFeature::UniqueId)));
doorsFeature.lockDoors();
} // eo lockDoors
}; // eo class Car
Given this, you can also go a step further and introduced named feature-sets (much like the option packs you get from a dealer/manufacturer) that can be automatically applied to a car, or range of makes, models and series.
Obviously, I've left a lot out. You may want to pass a reference to the car to each feature, or do otherwise.
Try rewriting your code to use vector instead of arrays. You can use just the space you need, and it's easier too.
#include <vector>
#include <memory>
class Car
{
public:
int getDoorCount() { return doors.size(); }
bool isFourWheelDrive() { return transmissionShafts.size() == 4; }
bool areDoorsAutoLocking() { return automaticDoorLocking.get() != NULL; }
void lockDoors() {
if (automaticDoorLocking.get() != NULL) {
automaticDoorLocking->lockDoors();
} else {
// Do manual door locking
}
}
private:
std::vector<Door> doors;
std::vector<TransmissionsShafts> transmissionShafts;
std::auto_ptr<DoorLockingElectronic> automaticDoorLocking;
};
Notice how Car now supports hatchbacks (5 doors).

C++ Class Delegation Constructor Problems

Thank you for reading.
The to delegate Class is called Sensor. It need a reference to be set in the Constructor like:
class Sensor { Sensor(other *ref);}
I have a Class testFactory. If i now type
class testFactor{
...stuff...
private:
Sensor mySensor;}
I get ALL the Problems. It cannot alloc an abstract Object. Or it cannot declare the variable, or does not know the Type of the variable.
Even taking Sensor out of the header into the cpp with as a static variable does not help.
Only if i change the Sensor Constructor to a void/non Constructor i dont get ANY Problems.
But then i have to use a setRed Function in the Sensor and this could lead to more problems.
Hope you can help me with: declaring a Variable with holds an Class with an non Void Constructor
You need to initialise the Sensor instance correctly - for example:
class TestFactor {
public:
TestFactor() : mySensor( 0 ) {}
private:
Sensor mySensor;
};
It works fine for me using c++. Perhaps you didn't declare the construction of Sensor in the initialisation list for Fac?
class Sensor {
public:
Sensor(int *a)
{
}
};
int b;
class Fac {
public:
Fac():
sensor(&b)
{}
private:
Sensor sensor;
};
main()
{
Fac a;
return 0;
}
One thing that I can see is that your constructor for Sensor is private (try changing class to struct or putting public: before constructor or declaring the frienship between Sensor and containing class). And you should either have a default constructor in addition to it or provide the parameter when instantiating it in containing class.
But you obviously need to be more specific to get more specific answers.
If you have classes with non-default constructors the compiler wont generate a default constructor for it. You also cannot instantiate classes which have only private constructors.
You can either provide a public default constructor, use a pointer to the instance or simply initialize the member via a public constructor:
class testFactor {
Sensor mySensor;
public:
testFactor() : mySensor(0) {}
};
One more point: If sensor is an abstract class, you cannot create an instance of it.
Most factory patterns have an abstract base classes an return pointers of the base class that point to allocated derived objects.
class Sensor
{
virtual std::string get_sensor_name(void) const = 0;
};
class Fire_Sensor
: public Sensor
{
std::string get_sensor_name(void) const
{ return "Fire Sensor";}
};
Sensor *
Sensor_Factory::create_sensor(std::string name)
{
if (name == "Fire Sensor")
{
return new Fire_Sensor;
}
return NULL;
}
Also look up reference slicing.