C++ Class Delegation Constructor Problems - c++

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.

Related

Factory Method pattern with unique_ptr member of a abstract class and Copy constructor

Suppose I have a setting with Abstract class ApplicatonBase which has a unique_ptr to another abstract class DocumentBase:
class ApplicationBase
{
public:
void factoryMethod()
{
_doc->doSomething();
};
protected:
std::unique_ptr<DocumentBase> _doc;
};
class DocumentBase
{
public:
virtual void doSomething() = 0;
};
Now I develop concrete classes RichDocument and RichApplication as follows:
class RichDocument : public DocumentBase
{
public:
void doSomething() override
{
std::cout << "I'm rich document\n";
}
};
class RichApplication : public ApplicationBase
{
public:
RichApplication()
{
_doc = std::unique_ptr<RichDocument>(new RichDocument());
}
RichApplication(const RichApplication& other)
{
/*
* TODO: I want to copy the data from other document
* unique_ptr and give it to the current document
* unique_ptr
*/
//Following crashes as the copy constructor is not known:
// error: no matching function for call to ‘RichDocument::RichDocument(DocumentBase&)
//_doc.reset(new RichDocument(*other._doc));
}
};
The problem is in the copy constructor. I want to deep copy the data in the unique_ptr in copy constructor. Is there a way to do that? Or should I change my structure? Any help would be appreciated.
Since you are pairing up RichDocument and RichApplication in the class hierarchy, you should be prepared to do one of the following:
Accept any base document when constructing a rich document, or
Reject all documents except RichDocument.
Assuming that the only way to initialize _doc is in the constructor of RichApplication, the second approach should be good enough:
RichDocument *otherDoc = dynamic_cast<RichDocument*>(other._doc.get());
// We created RichDocument in the constructor, so the cast must not fail:
assert(otherDoc);
_doc.reset(new RichDocument(*otherDoc));

Constructors and Copy Constructors accross Identical derived classes

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.

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.

C++ Initialize class static data member

I have a class which has a number of static function to perform some calculation. However, before the calculation, I need to pass in a data to initialize some of the static data members. Currently I have an init(data) function and a clearResource() function which should be called before and after the use of the class. Is there a better way of doing that?
For example:
classA(){
static int a;
static init(int b) {
a = b;
}
static functionA(){
//perform something based on value of a;
switch(a){
}
}
}
int main(){
classA::init(5);
classA::functionA();
}
Thanks
Avoid using static member functions : have your constructor initialize the data and the destructor clear the resources (see RAII). If the existing class cannot be changed, implement a helper class which calls init from its constructor and clearResource from its destructor.
You can use this kind of design
class A()
{
public:
static int a;
static void functionA(int arg = A::a)
{
if(A::a != arg)
A::a = arg;
...
}
};
int A::a = 0;
int main()
{
A::functionA();
}
You should apply the RAII concept: see this and this questions.
Make the member functions and data non-static, initialize in a constructor and free resources in the destructor. This will guarantee the correct sequence of calls: initialize - perform operations - free resources in the client code.
I'd avoid using static members in this case.
This is your problem. You have a class that does processing on some data. That data, for whatever reason, needs to be shared across all instances of this processing class. Ok then, we have a non-static solution!
class Data : boost::noncopyable
{
public:
Data()
{
// initialise all of our data.
}; // eo ctor
}; // eo class Data
Where you instantiate this class is up to you. It could be a member of an application class that is run at start up, or part of some root. It just needs to be accessible and does not need to be static nor a singleton.
class DataProcessor
{
private:
Data& m_Data;
public:
DataProcessor(Data& _data) : m_Data(_data)
{
}; // eo ctor
}; // eo class DataProcessor

Using a C++ child class instance as a default parameter?

So I have a couple classes defined thusly:
class StatLogger {
public:
StatLogger();
~StatLogger();
bool open(<parameters>);
private:
<minutiae>
};
And a child class that descends from it to implement a null object pattern (unopened it's its own null object)
class NullStatLogger : public StatLogger {
public:
NullStatLogger() : StatLogger() {}
};
Then I have a third class that I want to take an optional logger instance in its constructor:
class ThirdClass {
public:
ThirdClass(StatLogger& logger=NullStatLogger());
};
My problem is when I do it as above, I get:
error: default argument for parameter
of type ‘StatLogger&’ has type
‘NullStatLogger’
And if I put an explicit cast in the definition, I get:
error: no matching function for call
to
‘StatLogger::StatLogger(NullStatLogger)
Complaining about not having a constructor from a NullStatLogger even though it's a child class. What am I doing wrong here, is this allowed in C++?
I you want to use inheritance and polymorphism, ThirdClass needs to use either a pointer or a reference to StatLogger object, not with an actual object. Likewise, under the circumstances you almost certainly need to make StatLogger::~StatLogger() virtual.
For example, modified as follows, the code should compile cleanly:
class StatLogger {
public:
StatLogger();
virtual ~StatLogger();
// bool open(<parameters>);
private:
// <minutiae>
};
class NullStatLogger : public StatLogger {
public:
NullStatLogger() : StatLogger() {}
};
class ThirdClass {
StatLogger *log;
public:
ThirdClass(StatLogger *logger=new NullStatLogger()) : log(logger) {}
};
Edit: If you prefer a reference, the code looks something like this:
class StatLogger {
public:
StatLogger();
virtual ~StatLogger();
// bool open(<parameters>);
private:
// <minutiae>
};
class NullStatLogger : public StatLogger {
public:
NullStatLogger() : StatLogger() {}
};
class ThirdClass {
StatLogger &log;
public:
ThirdClass(StatLogger &logger=*new NullStatLogger()) : log(logger) {}
};
Based on the discussion in Jerry's answer, what about simplifying the problem by not using a default variable at all:
class ThirdClass
{
StatLogger log;
public:
ThirdClass() : log(NullLogger()) {}
ThirdClass(const StatLogger& logger) : log(logger) {}
};
There is no problem in using a derived instance as default argument for a base reference.
Now, you cannot bind a non-constant reference to a temporary (rvalue) which can be one reason for the compiler to complain about your code, but I would expect a better diagnose message (cannot bind temporary to reference or something alike).
This simple test compiles perfectly:
class base {};
class derived : public base {};
void f( base const & b = derived() ) {} // note: const &
int main() {
f();
}
If the function must modify the received argument consider refactoring to a pointer and provide a default null value (not a default dynamically allocated object).
void f( base * b = 0) {
if (b) b->log( "something" );
}
Only if you want to keep the non-const reference interface and at the same time provide a default instance, then you must provide an static instance, but I would recommend against this:
namespace detail {
derived d;
// or:
derived & null_logger() {
static derived log;
return log;
}
}
void f( base & b = detail::d ) {}
// or:
void g( base & b = detail::default_value() ) {}
Well for a default value I believe you have to provide a default value...
ThirdClass(StatLogger *logger = NULL)
for example
Uh, I know this is an oooold question, but I just had the exact same problem, and after reading all the proposed answers and comments, I came up with a slightly different solution.
I think it also might just be appropriate for the problem instance presented here, so here it goes:
Make the NullStartLogger a singleton type of object!
For me, it was quite elegant and sort. Very shortly, singleton is an object that you can not construct at will, since only and exactly one instance can exist at all time. (Alternatively, there might be 0 instances before the first usage, since you can postpone the initialization). You can of course only add the singleton functionality in to your derived class, while all the other instances (and derivations) of the parent class can be initialized and created normally. But, if NullStatLogger is, as it was in my case, just a dummy class, it does not store any data externally and does not have different behavior depending on the instance/init parameters, singleton class fits well.
Here's a short code snipped making your NullStatLogger a singleton, as well as a way to use it in the ThirdClass:
class NullStatLogger : public StatLogger {
private:
NullStatLogger() : StatLogger() {}
static NullStatLogger *_instance;
public:
static NullStatLogger &instance();
};
NullStatLogger::_instance = 0;
NullStatLogger &NullStatLogger:instance() {
if (_instance == 0)
_instance = new NullStatLogger(); // constructor private, this is
// the only place you can call it
return *_instance; // the same instance always returned
}
class ThirdClass {
public:
ThirdClass(StatLogger& logger=NullStatLogger::instance());
};
I know this surely won't help to whomever asked the question, but hopefully it helps someone else.