C++ calling objects from another class - c++

I asked this question here: C++ Method chaining with classes
In essesance, what I am trying to do is call a Constructor/Method from another class using Method chaining. Let's say I have 2 classes:
class Signal {
public:
Signal() { } // constructor
Signal& ParseSignal() {
// In this method I want to call
// the constructor "Parse()"
}
protected:
std::vector<double> data;
};
And I have another class called Parse:
class Parse {
public:
Parse() {
// This is the implementation
// I need to access the "data" contained in class "Signal
};
My main objective would be to do the following in main:
Signal s = Signal().ParseSignal();
This would then accept the signal, and, Parse this.
Someone suggested that I should use CRTP however, due to the fact that the base class (in this case Signal) has to have a template<> argument, this is not possible due to other classes inheriting.
Is there another solution to this problem?
EDIT:
I have tried the following, however, it looks like a dirty implementation and I cannot access the member variable:
class Parser {
public:
Parser() {
parse();
}
void parse() {
cout << "YES";
}
};
class Signal {
public:
friend class Parser;
Signal() { val = 0;}
Signal& Parse() {
Parser::Parser();
return *(this);
}
protected:
int val;
};

You implicitly cannot and should not do what you appear to be trying to do, which is to call the constructor of a class without constructing an instance of the class.
If you want the behavior of Parser in Signal, then you have at least three options: 1. Inherit Parser, 2. Add a Parser member, 3. Create a "Parseable" interface-class which Parser can take as an argument.
class Parser {
public:
class Interface {
public:
std::vector<double> m_data;
};
Parser(Interface& interface) {
parse(interface);
}
};
class SignalInheriting : public Parser::Interface {
public:
SignalInheriting() {
Parser p(*this); // can take the Parser::Interface view of this object.
}
};
class SignalMember {
Parser::Interface m_parserIface;
public:
SignalMember() : m_parserIface() {
}
};
Doing heavy lifting in constructors like this is great for obfuscated or dog-show code, but is terrible for production systems that require any kind of maintenance.
But if you're fine with having to diagnose problems in code that works hands-free like this at 3am on a Saturday when you're hung over - then go for it.
A major factor to which pattern you should choose is how long the parse-related data is going to persist vs how long the Signal objects are going to persist.
Conversely, if the Signal object is little more than a specialization of the "Parse" API, then just inherit Parse and be done with.

The simplest way to do what you are trying to do would be something like this:
class Parse {
public:
Parse(std::vector<double> &data) {
// do stuff
}
};
class Signal {
public:
Signal() { } // constructor
Signal& ParseSignal() {
Parse parser(data);
return *this;
}
protected:
std::vector<double> data;
};
However I suggest that you take a look at the Visitor Pattern for a more generic solution.
Or at the very least don't do the work in the Parse constructor, do it in some method instead.

Related

Namespace Functions within Class alternatives?

I'd like to be able to group similar functions in a class into a group so I don't need to append each name with what it's about.
I've seen this question which says that you can't have namespaces within classes. I've also seen this question which proposes using strongly typed enums. The problem here though, is that I'm not sure whether or not these enums can actually accomodate functions?
The problem contextualised:
class Semaphore
{
public:
void Set(bool State){Semaphore = State;}
bool Get(){return Semaphore;}
void Wait()
{
while (Semaphore)
{
//Wait until the node becomes available.
}
return;
}
private:
bool Semaphore = 0; //Don't operate on the same target simultaneously.
};
class Node : Semaphore
{
public:
unsigned long IP = 0; //IP should be stored in network order.
bool IsNeighbour = 0; //Single hop.
std::vector<int> OpenPorts;
//Rest of code...
};
Currently, NodeClass.Get() is how I can get the semaphore. However this introduces confusion as to what Get() actually gets. I'd like to have something akin to NodeClass.Semaphore::Get(). Otherwise I'd have to have the functions as SemaphoreSet(), SemaphoreGet(), and SemaphoreWait(), which isn't too well organised or nice looking.
I had thought of just having the Semaphore class on it's own, and instantiating it within the other classes, but if I could stick with the inheritance approach, that would be nicer.
So essentially, is it possible to access inherited methods like InheritedClass.Group::Function()?
If you really want to do this, you could force the user to call with the base class name by deleteing the member function in the subclass:
class Base {
public:
void Set(bool) { }
};
class Derived : public Base {
public:
void Set(bool) = delete;
};
int main() {
Derived d;
// d.Set(true); // compiler error
d.Base::Set(true);
}
However, if the semantics of calling Set on the subclass are significantly different than what you'd expect them to be when calling Set on the base class, you should probably use a data member and name a member function accordingly as you've described:
class Base {
public:
void Set(bool) { }
};
class Derived {
public:
void SetBase(bool b) {
b_.Set(b);
}
private:
Base b_;
};
int main() {
Derived d;
d.SetBase(true);
}

Proper design setup for derived classes with common attributes but different values

So I can think of a few ways to do this but I feel like I am just retyping the same thing with each new subclass. Is there a design pattern where I can set up the full structure for my subclasses in a way where I reduce the amount of code needed for implementation (and also enforce proper implementation if possible?)
This seems simple but the ideas I've had don't work, and the best I've found is to either hard code in the parameters when calling the constructor or to set up new constants within each child class then use those.
What I currently have is something like this:
"parent.hpp"
class Parent {
private:
std::string name;
int someValue;
protected:
Parent(std::string name, int someValue); // NOTE: There will be 7 parameters/attributes that need initial base values
void setName(std::string name) { this->name = name; }
void setSomeValue(int someValue) { this->someValue = someValue; }
public:
std::string getName() { return this->name; }
int getSomeValue() { return this->someValue; }
};
"parent.cpp"
Parent::Parent(std::string name, int someValue) {
setName(name);
setSomeValue(someValue);
}
"child.hpp"
class Child : public Parent {
public:
Child();
};
"child.cpp - option 1"
static const std::string DEFAULT_NAME = "Jon";
static const int DEFAULT_SOME_VALUE = 100;
Child::Child() : Parent(DEFAULT_NAME, DEFAULT_SOME_VALUE) {
// other stuff if needed
}
"child.cpp - option 2"
Child::Child() : Parent("Jon", 100) {
// other stuff if needed
}
There will be virtual methods and such I'll add later, but for now I just want to know of the right design pattern for having (potentially) many subclasses. There are also more parameters that will be in common which are all int values. It would seem unclear to me to have the constructors be Child::Child("string", 1, 2, 3, 4, 5, 6) albeit it would be easier to implement new subclasses.
On the other hand if I am just retyping the boiler plate constants for the base values in each subclass, the constructors will be more descriptive, but there would be a lot of code reuse.
It would seem to me what I would want to do is have virtual protected constants in the Parent class which the Child classes would need to define, then call those from the constructors, but that is not allowed. Is one of the two options a better one? Is there a better "long-term" setup for this?
I looked through all of the Similar Questions and the closest I found was this: Proper way to make base class setup parent class. Though I'm not really sure if that idea would fix my issue or make anything clearer.
Another idea I had was to call pure virtual methods from the default constructor, but as I learned that is also not allowed.
I would use another object to hold the state like Ami, although I would have done it for a different reason. Since the state is a separate class, you can fully construct it before the actual Parent and Child are constructed, and it can have its own hierarcy.
header
class Parent {
protected:
struct ParentState {
std::string name;
int someValue;
};
Parent(ParentState);
void setName(std::string name) { data.name = name; }
void setSomeValue(int someValue) { data.someValue = someValue; }
public:
std::string getName() { return data.name; }
int getSomeValue() { return data.someValue; }
private:
ParentState data;
};
class Child : public Parent {
struct ChildDefaults : public Parent::ParentState {
ChildDefaults();
};
public:
Child();
};
implementation
Parent::Parent(ParentState init) {
// since you have setters, they should be used
// instead of just data=init;
setName(init.name);
setSomeValue(init.someValue);
}
Child::ChildDefaults::ChildDefaults(){
name = "Jon";
someValue = 100;
}
Child::Child() : Parent(ChildDefaults()){
// other stuff if needed
}
If you put the ParentState and ChildDefault classes in a separate file, you can use that file to put all the defaults in one place where you can easily look them up or change them. They also might be prettier if they are not hidden inside the classes, forcing the extra scope syntax.
addendum:
To put the whole default settings heirarchy together in its own header, just move them all to one header. Be sure to do an include guard to avoid multiply defining the constructors.
#ifndef THE_DEFAULTS_H
#define THE_DEFAULTS_H
struct ParentState {
std::string name;
int someValue;
};
struct ChildDefaults : public Parent::ParentState {
ChildDefaults() {
name = "Jon";
someValue = 100;
}
};
// more default settings for other classes
#endif
Perhaps you could combine here two ideas:
Avoiding a large number of args passed to a function in general (including a ctor).
Method chaining.
(The first one is more fundamental here, and the second one is less essintial, and is here just for improved readability.)
In more detail:
Having any function, a ctor of a base class in particular, taking 7 parameters, seems very verbose & fragile. Suppose you realize that you needed to add another parameter. Would you now have to go over all the derived classes? That's problematic.
So let's start with something like:
class Parent
{
protected:
explicit Parent(const ParentParams &params);
};
And ParentParams looks something like this:
class ParentParams
{
public:
// Initialize with default stuff.
ParentParams();
// Changing only the foo aspect (via method chaining).
ParentParams &setFoo(Foo foo_val)
{
m_foo = foo_val;
return *this;
}
// Changing only the bar aspect (via method chaining).
ParentParams &setBar(Bar bar_val)
{
m_bar = bar_val;
return *this;
}
// Many more - you mentioned at least 7.
....
};
Now a child could look something like this:
// A child that happens to have the property that it changes foo and bar aspects.
class FooBarChangingChild :
public Parent
{
public:
FooBarChangingChild();
};
And in its implementation:
// Static cpp function just creating the params.
static ParentParams makeParams()
{
// Note the clarity of which options are being changed.
return ParentParams()
.setFoo(someFooVal)
.setBar(someBarVal);
}
FooBarChangingChild::FooBarChangingChild() :
Parent(makeParams())
{
}

oop - C++ - Proper way to implement type-specific behavior?

Let's say I have a parent class, Arbitrary, and two child classes, Foo and Bar. I'm trying to implement a function to insert any Arbitrary object into a database, however, since the child classes contain data specific to those classes, I need to perform slightly different operations depending on the type.
Coming into C++ from Java/C#, my first instinct was to have a function that takes the parent as the parameter use something like instanceof and some if statements to handle child-class-specific behavior.
Pseudocode:
void someClass(Arbitrary obj){
obj.doSomething(); //a member function from the parent class
//more operations based on parent class
if(obj instanceof Foo){
//do Foo specific stuff
}
if(obj instanceof Bar){
//do Bar specific stuff
}
}
However, after looking into how to implement this in C++, the general consensus seemed to be that this is poor design.
If you have to use instanceof, there is, in most cases, something wrong with your design. – mslot
I considered the possibility of overloading the function with each type, but that would seemingly lead to code duplication. And, I would still end up needing to handle the child-specific behavior in the parent class, so that wouldn't solve the problem anyway.
So, my question is, what's the better way of performing operations that where all parent and child classes should be accepted as input, but in which behavior is dictated by the object type?
First, you want to take your Arbitrary by pointer or reference, otherwise you will slice off the derived class. Next, sounds like a case of a virtual method.
void someClass(Arbitrary* obj) {
obj->insertIntoDB();
}
where:
class Arbitrary {
public:
virtual ~Arbitrary();
virtual void insertIntoDB() = 0;
};
So that the subclasses can provide specific overrides:
class Foo : public Arbitrary {
public:
void insertIntoDB() override
// ^^^ if C++11
{
// do Foo-specific insertion here
}
};
Now there might be some common functionality in this insertion between Foo and Bar... so you should put that as a protected method in Arbitrary. protected so that both Foo and Bar have access to it but someClass() doesn't.
In my opinion, if at any place you need to write
if( is_instance_of(Derived1) )
//do something
else if ( is_instance_of(Derived2) )
//do somthing else
...
then it's as sign of bad design. First and most straight forward issue is that of "Maintainence". You have to take care in case further derivation happens. However, sometimes it's necessary. for e.g if your all classes are part of some library. In other cases you should avoid this coding as far as possible.
Most often you can remove the need to check for specific instance by introducing some new classes in the hierarchy. For e.g :-
class BankAccount {};
class SavingAccount : public BankAccount { void creditInterest(); };
class CheckingAccount : public BankAccount { void creditInterest(): };
In this case, there seems to be a need for if/else statement to check for actual object as there is no corresponsing creditInterest() in BanAccount class. However, indroducing a new class could obviate the need for that checking.
class BankAccount {};
class InterestBearingAccount : public BankAccount { void creditInterest(): } {};
class SavingAccount : public InterestBearingAccount { void creditInterest(): };
class CheckingAccount : public InterestBearingAccount { void creditInterest(): };
The issue here is that this will arguably violate SOLID design principles, given that any extension in the number of mapped classes would require new branches in the if statement, otherwise the existing dispatch method will fail (it won't work with any subclass, just those it knows about).
What you are describing looks well suited to inheritance polymorphicism - each of Arbitrary (base), Foo and Bar can take on the concerns of its own fields.
There is likely to be some common database plumbing which can be DRY'd up the base method.
class Arbitrary { // Your base class
protected:
virtual void mapFields(DbCommand& dbCommand) {
// Map the base fields here
}
public:
void saveToDatabase() { // External caller invokes this on any subclass
openConnection();
DbCommand& command = createDbCommand();
mapFields(command); // Polymorphic call
executeDbTransaction(command);
}
}
class Foo : public Arbitrary {
protected: // Hide implementation external parties
virtual void mapFields(DbCommand& dbCommand) {
Arbitrary::mapFields();
// Map Foo specific fields here
}
}
class Bar : public Arbitrary {
protected:
virtual void mapFields(DbCommand& dbCommand) {
Arbitrary::mapFields();
// Map Bar specific fields here
}
}
If the base class, Arbitrary itself cannot exist in isolation, it should also be marked as abstract.
As StuartLC pointed out, the current design violates the SOLID principles. However, both his answer and Barry's answer has strong coupling with the database, which I do not like (should Arbitrary really need to know about the database?). I would suggest that you make some additional abstraction, and make the database operations independent of the the data types.
One possible implementation may be like:
class Arbitrary {
public:
virtual std::string serialize();
static Arbitrary* deserialize();
};
Your database-related would be like (please notice that the parameter form Arbitrary obj is wrong and can truncate the object):
void someMethod(const Arbitrary& obj)
{
// ...
db.insert(obj.serialize());
}
You can retrieve the string from the database later and deserialize into a suitable object.
So, my question is, what's the better way of performing operations
that where all parent and child classes should be accepted as input,
but in which behavior is dictated by the object type?
You can use Visitor pattern.
#include <iostream>
using namespace std;
class Arbitrary;
class Foo;
class Bar;
class ArbitraryVisitor
{
public:
virtual void visitParent(Arbitrary& m) {};
virtual void visitFoo(Foo& vm) {};
virtual void visitBar(Bar& vm) {};
};
class Arbitrary
{
public:
virtual void DoSomething()
{
cout<<"do Parent specific stuff"<<endl;
}
virtual void accept(ArbitraryVisitor& v)
{
v.visitParent(*this);
}
};
class Foo: public Arbitrary
{
public:
virtual void DoSomething()
{
cout<<"do Foo specific stuff"<<endl;
}
virtual void accept(ArbitraryVisitor& v)
{
v.visitFoo(*this);
}
};
class Bar: public Arbitrary
{
public:
virtual void DoSomething()
{
cout<<"do Bar specific stuff"<<endl;
}
virtual void accept(ArbitraryVisitor& v)
{
v.visitBar(*this);
}
};
class SetArbitaryVisitor : public ArbitraryVisitor
{
void visitParent(Arbitrary& vm)
{
vm.DoSomething();
}
void visitFoo(Foo& vm)
{
vm.DoSomething();
}
void visitBar(Bar& vm)
{
vm.DoSomething();
}
};
int main()
{
Arbitrary *arb = new Foo();
SetArbitaryVisitor scv;
arb->accept(scv);
}

Enforce static method overloading in child class in C++

I have something like this:
class Base
{
public:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
template <typename T>
int Produce()
{
return T::Lolz();
}
and
Produce<Base>();
Produce<Child>();
both return 0, which is of course correct, but unwanted. Is there anyway to enforce the explicit declaration of the Lolz() method in the second class, or maybe throwing an compile-time error when using Produce<Child>()?
Or is it bad OO design and I should do something completely different?
EDIT:
What I am basically trying to do, is to make something like this work:
Manager manager;
manager.RegisterProducer(&Woot::Produce, "Woot");
manager.RegisterProducer(&Goop::Produce, "Goop");
Object obj = manager.Produce("Woot");
or, more generally, an external abstract factory that doesn't know the types of objects it is producing, so that new types can be added without writing more code.
There are two ways to avoid it. Actually, it depends on what you want to say.
(1) Making Produce() as an interface of Base class.
template <typename T>
int Produce()
{
return T::Lolz();
}
class Base
{
friend int Produce<Base>();
protected:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
int main(void)
{
Produce<Base>(); // Ok.
Produce<Child>(); // error :'Base::Lolz' : cannot access protected member declared in class 'Base'
}
(2) Using template specialization.
template <typename T>
int Produce()
{
return T::Lolz();
}
class Base
{
public:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
template<>
int Produce<Child>()
{
throw std::bad_exception("oops!");
return 0;
}
int main(void)
{
Produce<Base>(); // Ok.
Produce<Child>(); // it will throw an exception!
}
There is no way to override a static method in a subclass, you can only hide it. Nor is there anything analogous to an abstract method that would force a subclass to provide a definition. If you really need different behaviour in different subclasses, then you should make Lolz() an instance method and override it as normal.
I suspect that you are treading close to a design problem here. One of the principals of object-oriented design is the substitution principal. It basically says that if B is a subclass of A, then it must be valid to use a B wherever you could use an A.
C++ doesn't support virtual static functions. Think about what the vtable would have to look like to support that and you'll realize its a no-go.
or maybe throwing a compile-time error when using Produce<Child>()
The modern-day solution for this is to use delete:
class Child : public Base
{
public:
int nothing;
static int Lolz() = delete;
};
It helps avoid a lot of boilerplate and express your intentions clearly.
As far as I understand your question, you want to disable static method from the parent class. You can do something like this in the derived class:
class Child : public Base
{
public:
int nothing;
private:
using Base::Lolz;
};
Now Child::Lolz becomes private.
But, of course, it's much better to fix the design :)

How should I distinguish between subclasses

I have a token class that looks something like this:
class Token
{
public:
typedef enum { STRTOK, INTTOK } Type;
virtual bool IsA(Type) = 0;
}
class IntTok : public Token
{
int data;
public:
bool IsA(Type t) { return (t == INTTOK); }
int GetData() { return data; }
}
IntTok newToken;
if ( newToken.IsA(Token::INTTOK )
{
//blah blah
}
So essentially I have to have every subclass defined in the Token class; which doesn't turn out that bad because there are very few subclasses and I can't imagine them changing. But still, it's ugly, kludgy and less "correct" than identifying subclasses using a dynamic cast. However:
IntTok newToken;
IntTok* tmpTokenTest = dynamic_cast<IntTok*>(&newToken);
if ( tmpTokenTest != NULL )
{
//blah blah
}
Is also pretty kludgy. Particularly when I have to string them together in a large, nested if.
So which would you use? Is there another solution to this problem?
Note: I know that I'll have to cast them to get at their respective data anyways, but
I won't be casting them until right before I use their function, so it feels cleaner and
I test their type far more often then I use their data.
Note2: Not indicated in the code above is that these tokens are also a linked list. That makes templating difficult(a Token<int> may point to a Token<string>, etc). Which is why I need a Token class as a parent to begin with.
Just use virtual functions instead to do what you want. Instead of this:
if(newToken.IsA(Token::INTTOK))
{
// do stuff with ((IntTok*)&newToken)->GetData()
}
Do this:
class Token
{
public:
...
virtual void doTypeDependentStuff() {} // empty default implementation
}
class IntTok : public Token
{
public:
...
void doTypeDependent()
{
// do stuff with data
}
}
Visitor pattern, indeed.
class TokenVisitor {
public:
virtual ~TokenVisitor() { }
virtual void visit(IntTok&) = 0;
virtual void visit(StrTok&) = 0;
};
class Token {
public:
virtual void accept(TokenVisitor &v) = 0;
};
class IntTok : public Token {
int data;
public:
virtual void accept(TokenVisitor &v) {
v.visit(*this);
}
int GetData() { return data; }
};
Then just implement the visitor interface and call
token->accept(myVisitor);
Control will be given to the Visitor, which then can do the appropriate action(s). If you need to have the variable locally and of the right type - then however you will hardly get around down-casting it. But i think driving control to specific implementations using virtual functions often is a good way to solve it.
Might i suggest using Boost::Variant, which is basically the union of multiple types (an object of type variant can hold any object of type Ti ( 1 <= i <= n ) ).
Using this, you won't have to use inheritance.
See there for more information.
So essentially I have to have every subclass defined in the Token class
Can you explain why?
Is it really necessary to cast? Polymorphic functions can be put to use.
Or, maybe you can have a templated Token class (with default behavior for some) and specialize for the remaining.
That's a nasty one, though I would be more likely to go with the version of using RTTI.
Weren't new C++ compilers (I've last tried in VC 6.0 when it wasn't really supported) supposed the typeid operator so you wouldn't need a full dynamic cast?