Multiple inheritance and singleton design pattern - c++

I have the following class hierarchy set up and would like the print() function of the non-singleton base object OtherBase to be called which in turn calls the printSymbol() from one of the child classes, in this case SingletonChild. I understand this is a complicated and somewhat unnecessary looking hierarchy and way of doing things but this is an assignment and I am required to do it in this way.
An example of my problem is as follows:
#include <iostream>
using namespace std;
class Object
{
virtual void print() = 0;
};
class SingletonBase : public Object
{
private:
static SingletonBase* theOnlyTrueInstance;
protected:
SingletonBase()
{
if(!theOnlyTrueInstance)
theOnlyTrueInstance = this;
}
virtual ~SingletonBase(){}
public:
static SingletonBase* instance()
{
if (!theOnlyTrueInstance) initInstance();
return theOnlyTrueInstance;
}
void print()
{ cout<<"Singleton"<<endl; }
static void initInstance()
{ new SingletonBase; }
};
SingletonBase* SingletonBase::theOnlyTrueInstance = 0;
class OtherBase : public Object
{
public:
virtual string printSymbol() = 0;
void print()
{ cout<<printSymbol(); }
};
class SingletonChild : public SingletonBase , public OtherBase
{
public:
string printSymbol()
{
return "Test";
}
static void initInstance()
{ new SingletonChild; }
};
int main() {
SingletonChild::initInstance();
OtherBase* test = (OtherBase*) SingletonChild::instance();
test->print();
return 0;
}
How can I get the instance test to call the print function of the one base class OtherBase and not the Singleton base class SingletonBase?
I have tried test->OtherBase::print(), but this did not work.

#MuhammadAhmad's answer is basically right. I would like to add that the main issue here is that a C-style cast is allowing you to do something that you really don't want to do. Because you can't statically cast a SingletonBase to an OtherBase, the C-style cast is doing a reinterpret_cast instead, and calling print() on the resulting pointer is undefined behavior. If you had used a static_cast, you would have gotten an error:
OtherBase* test = static_cast<OtherBase*>(SingletonChild::instance());
error: invalid static_cast from type ‘SingletonBase*’ to type ‘OtherBase*’
This may have led you to realize you needed to do things a bit differently. For example, you can use a dynamic_cast to cast sideways like this.

SingletonChild is inheriting it's instance method from SingletonBase, which is returning a pointer to SingletonBase.
So calling SingletonChild::instance(); will get you a SingletonBase*, which you can't simply cast to OtherBase*
Try casting it to SingletonChild* first, then to OtherBase*:
OtherBase* test = (OtherBase*)((SingletonChild*)SingletonChild::instance());
And then call the print method simply like this: test->print();
See the code on ideone.
EDIT:
You can also achieve this like this:
SingletonChild* test = (SingletonChild*)SingletonChild::instance();
test->OtherBase::print();
See this method in action too.

What you are trying to do is casting an object of type SingletonBase* to type OtherBase*, which is not possible because SingletonBase does not derive from OtherBase. If you had used dynamic_cast rather than old, deprecated C-style cast, you would have recognized this situation rather immediately.
To solve the issue, you need to modify the code as follows:
class Object
{
virtual void print() = 0;
};
class SingletonBase : public Object
{
private:
static Object* theOnlyTrueInstance;
protected:
SingletonBase()
{
if(!theOnlyTrueInstance)
theOnlyTrueInstance = this;
}
virtual ~SingletonBase(){}
public:
static Object* instance()
{
if (!theOnlyTrueInstance) initInstance();
return theOnlyTrueInstance;
}
void print()
{ cout<<"Singleton"<<endl; }
static void initInstance()
{ new SingletonBase; }
};
Object* SingletonBase::theOnlyTrueInstance = 0;
class OtherBase : public Object
{
public:
virtual string printSymbol() = 0;
void print()
{ cout<<printSymbol(); }
};
class SingletonChild : public SingletonBase , public OtherBase
{
public:
string printSymbol()
{
return "Test";
}
static void initInstance()
{ new SingletonChild; }
};
int main() {
SingletonChild::initInstance();
OtherBase* test = dynamic_cast<OtherBase*>(SingletonChild::instance());
test->print();
return 0;
}
You should avoid C-style casts, as you could end-up manipulating object like something they are not.

Related

How do I cast a templated class

I have an example like the one below in C++ where I receive a pointer to base class, exampleParent, and would like to cast it to a pointer to the inherited class example (in reality I just want to call a function on example) . The caveat is that the inherited class is templated. In the example below, I know the template is of type int so there is no problem. In general, what would be a good way to do this if I am not aware before hand the type of the template?
class exampleParent{};
template<typename P>
class example: public exampleParent
{
public:
int do_something() const
{
std::cout<<"I am doing something"<<std::endl;
return 0;
}
};
boost::shared_ptr<const exampleParent> getPtr()
{
return boost::make_shared<const example<int>>();
}
int main()
{
boost::shared_ptr<const exampleParent> example = getPtr();
auto example_ptr = boost::dynamic_pointer_cast<const example<int>>(example);
return example_ptr-> do_something();
}
One solution I propose is to change the code to something like this:
class exampleParent{};
class something_interface: public exampleParent
{
public:
virtual int do_something() const = 0 ;
};
template<typename P>
class example: public something_interface
{
public:
int do_something() const override
{
std::cout<<"I am doing something"<<std::end;
return 0;
}
};
boost::shared_ptr<const exampleParent> getPtr()
{
return boost::make_shared<const example<int>>();
}
int main()
{
boost::shared_ptr<const exampleParent> example = getPtr();
auto example_ptr = boost::dynamic_cast<const something_interface>(example);
return example_ptr->do_something();
}
This would work, but it feels a bit of a hack: something_interface should not really exist, as it has no object oriented interpretation in itself.
Any help would be appreciated!
If you can make exampleParent an abstract class (if you can modify that class at all), that would be the best:
class exampleParent
{
public:
virtual ~exampleParent() = default;
virtual int do_something() const = 0;
};
template<typename P>
class example: public exampleParent
{
public:
int do_something() const override
{
std::cout<<"I am doing something"<<std::endl;
return 0;
}
};
Then you don't need a cast to invoke that method.
If you cannot touch this exampleParent class, go on with the intermediate one as you proposed, but remember to actually inherit exampleParent and don't throw exception, just make the method pure virtual:
class intermediate: public exampleParent
{
public:
~intermediate() override = default;
virtual int do_something() const = 0;
};
Otherwise the only way is to do dynamic_pointer_cast for all possible types and check the cast result, because different instances of template class are just different types in general. Of course it doesn't make sense if there is infinite number of possible template parameters P.

Convert derived class to generic class type with the same public functions, while still being able to call the function of the derived class

In the program hereafter, I have a class animal, that has derived classes cat and dog with the same public functions but different private functions. I would like to let the user decide during runtime which animal is being created. I have made a simple example that shows what I approximately want, but which obviously doesn't work. I don't know how to solve this and would like to have your help.
#include <cstdio>
class canimal
{
public:
int sound()
{
std::printf("...\n");
return 0;
}
};
class cdog : public canimal
{
public:
int sound()
{
std::printf("Woof!\n");
return 0;
}
};
class ccat : public canimal
{
public:
int sound()
{
std::printf("Mieau!\n");
return 0;
}
};
int main()
{
canimal *animal;
cdog *dog;
// I would like to let the user decide here which animal will be made
// In this case, I would like the function to say "Woof!", but of course it doesn't...
animal = new cdog;
animal->sound();
// Here it works, but I would like the pointer to be of the generic class
// such that the type of animal can be chosen at runtime
dog = new cdog;
dog->sound();
return 0;
}
You need to make the sound() method virtual:
class canimal
{
public:
virtual int sound()
^^^^^^^
This will make it behave exactly as you need.
For further discussion, see Why do we need Virtual Functions in C++?
In C++ 11 there is a new override keyword that, when used appropriately, makes certain types of errors less likely. See Safely override C++ virtual functions
I think you are looking to make sound() virtual. Read up on polymorphism in C++.
class canimal
{
public:
virtual int sound()
{
std::printf("...\n");
return 0;
}
};
You need to use virtual
i.e.
class canimal
{
public:
virtual int sound()
{
std::printf("...\n");
return 0;
}
};
class cdog : public canimal
{
public:
virtual int sound()
{
std::printf("Woof!\n");
return 0;
}
};
class ccat : public canimal
{
public:
virtual int sound()
{
std::printf("Mieau!\n");
return 0;
}
};

c++ design query

I am designing a framework in c++ which is supposed to provide basic functionality and act as interface for the other derived systems.
#include <stdio.h>
class Module
{
public:
virtual void print()
{
printf("Inside print of Module\n");
}
};
class ModuleAlpha : public Module
{
public:
void print()
{
printf("Inside print of ModuleAlpha\n");
}
void module_alpha_function() /* local function of this class */
{
printf("Inside module_alpha_function\n");
}
};
class System
{
public:
virtual void create_module(){}
protected:
class Module * module_obj;
};
class SystemAlpha: public System
{
public:
void create_module()
{
module_obj = new ModuleAlpha();
module_obj->print(); // virtual function, so its fine.
/* to call module_alpha_function, dynamic_cast is required,
* Is this a good practice or there is some better way to design such a system */
ModuleAlpha * module_alpha_obj = dynamic_cast<ModuleAlpha*>(module_obj);
module_alpha_obj->module_alpha_function();
}
};
main()
{
System * system_obj = new SystemAlpha();
system_obj->create_module();
}
Edited the code to be more logical and it compiles straight away. The question is, that is there a better way to design such a system, or dynamic_cast is the only solution. Also, if there are more derived modules, then for type-casting, there is some intelligence required in the base Module class.
If Derived is the only concrete instance of Base you could use static_cast instead.
Personally, I define a function, like MyCast for every specialized class. I define four overloaded variants, so that I can down-cast const and non-const pointers and references. For example:
inline Derived * MyCast(Base * x) { return static_cast<Derived *> (x); }
inline Derived const * MyCast(Base const * x) { return static_cast<Derived const *>(x); }
inline Derived & MyCast(Base & x) { return static_cast<Derived &> (x); }
inline Derived const & MyCast(Base const & x) { return static_cast<Derived const &>(x); }
And likewise for Derived2 and Base2.
The big advantage in having all four is that you will not change constness by accident, and you can use the same construct regardless if you have a pointer or a reference.
Of course, you could replace static_cast with a macro, and use dynamic_cast in debug mode and static_cast is release mode.
Also, the code above can easily be wrapped into a macro, making it easy to batch-define the functions.
Using this pattern, you could then implement your code as:
class Derived : public Base
{
public:
virtual void func2()
{
base2_obj = new Derived2();
}
void DerivedFunc()
{
MyCast(base2_obj)->Derived2Func();
}
}
The design gets much cleaner if Base does not contain the base_obj object, but rather gets a reference via a virtual method. Derived should contain a Derived2 object, like:
class Base
{
public:
virtual void func1();
private:
class Base2;
virtual Base2& get_base2();
};
class Derived : public Base
{
Derived2 derived2;
public:
Base2& get_base2() { return derived2; }
void DerivedFunc()
{
derived2->Derived2Func();
}
}
If you are worried about performance, pass the reference in the constructor of Base.
I took your code with its many compile errors and tried to simplify it. Is this what you are trying to acheive? It will compile.
class Base2 {
public:
virtual void Derived2Func(){
}
};
Base2* fnToInstantiateABase2();
class Base {
public:
Base() : base2_obj(fnToInstantiateABase2()) {
}
virtual void DerivedFunc() {
}
protected:
Base2* base2_obj;
};
class Derived : public Base {
public:
void DerivedFunc() {
base2_obj->Derived2Func(); // not possible as base2_obj is of type Base2
}
};
class Derived2 : public Base2 {
public:
void Derived2Func() {
}
};
void test() {
Base * base_obj = new Derived();
base_obj->DerivedFunc();
}
Base2* fnToInstantiateABase2() {
return new Derived2();
}

C++: Accessing variables present only in one of the derived classes

void func1()
{
}
class Base
{
public:
virtual void memfunc() = 0;
};
class DerivedA: public Base
{
public:
virtual void memfunc() = 0;
};
class Derived1: public DerivedA
{
public:
void memfunc()
{
func1();
}
};
class Derived2: public DerivedA
{
public:
int* pbuf;
int val;
void func2(int* pbuf,int val)
{
/* update pbuf depending on the value of val*/
}
void memfunc()
{
func1();
func2(pbuf,val);
}
};
class user{
public:
Base* mBase;
void userfunc()
{
mBase = f(); //Object pointer to Derived1/Derived2 will be assigned based on dynamic loading;
//Before calling the below func, I Need to assign value to the 'val' variable of the class 'Derived2'
mBase->memfunc();
}
};
int main()
{
user ouser;
ouser.userfunc();
return 0;
}
The variables val and pbuf are present in Derived2 only.
How can I assign values to them in userfunc/main as I don't know if the object mBase would point to Derived1/Derived2.
You can use dynamic_cast and check for NULL, which will be returned if the object isn't of type Derived2. If the cast succeeds, you can use all methods of Derived2.
Use a dynamic_cast in userfunc() and test for Derived2, i.e.
Derived2* p = dynamic_cast<Derived2*>(mBase);
if (p) // this is NULL if the above fails.
{
// initialize...
}
If val and pbuf are present only on Derived2, then you must have some way to identify them. You would need to create an enum Base::Type { Derived1, Derived2 }, set them on your derived classes, and test in main. Then, you can cast mBase to Derived2 if it is of that type, and set val.
If you are sure of the concrete type of your class you can use a dynamic_cast. Anyway that's a bad practice. The purpose of using a base abstract class reference is to hide internal details and specific implementations issues.
If you need to do so, maybe you can add a getProperty()/setProperty() method to your base class. Something like:
class Base
{
public:
virtual void memfunc() = 0;
virtual void setProperty(String name, Property prop);
virtual Property getProperty(String name);
};
Use typeid:
http://en.wikipedia.org/wiki/Typeid

Simulating a virtual static member of a class in c++?

Is there anyway to have a sort of virtual static member in C++?
For example:
class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?
class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes.
Any idea?
Here is one solution:
struct BaseData
{
const string my_word;
const int my_number;
};
class Base
{
public:
Base(const BaseData* apBaseData)
{
mpBaseData = apBaseData;
}
const string getMyWord()
{
return mpBaseData->my_word;
}
int getMyNumber()
{
return mpBaseData->my_number;
}
private:
const BaseData* mpBaseData;
};
class Derived : public Base
{
public:
Derived() : Base(&sBaseData)
{
}
private:
static BaseData sBaseData;
}
BaseData Derived::BaseData = { "Foo", 42 };
It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class.
If you insist on having the "shared" members implemented as static members of the derived class, you might be able to auto-generate the code of the derived classes. XSLT is a great tool for auto-generating simple classes.
In general, the example doesn't show a need for "virtual static" members, because for purposes like these you don't actually need inheritance - instead you should use the base class and have it accept the appropriate values in the constructor - maybe creating a single instance of the arguments for each "sub-type" and passing a pointer to it to avoid duplication of the shared data. Another similar approach is to use templates and pass as the template argument a class that provides all the relevant values (this is commonly referred to as the "Policy" pattern).
To conclude - for the purpose of the original example, there is no need for such "virtual static" members. If you still think they are needed for the code you are writing, please try to elaborate and add more context.
Example of what I described above:
class BaseClass {
public:
BaseClass(const Descriptor& desc) : _desc(desc) {}
string GetName() const { return _desc.name; }
int GetId() const { return _desc.Id; }
X GetX() connst { return _desc.X; }
virtual void UseClass() = 0;
private:
const Descriptor _desc;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(Descriptor("abc", 1,...)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass("Wowzer", 843,...) {}
virtual void UseClass() { /* do something */ }
};
I'd like to elaborate on this solution, and maybe give a solution to the de-initialization problem:
With a small change, you can implement the design described above without necessarily create a new instance of the "descriptor" for each instance of a derived class.
You can create a singleton object, DescriptorMap, that will hold the single instance of each descriptor, and use it when constructing the derived objects like so:
enum InstanceType {
Yellow,
Big,
BananaHammoc
}
class DescriptorsMap{
public:
static Descriptor* GetDescriptor(InstanceType type) {
if ( _instance.Get() == null) {
_instance.reset(new DescriptorsMap());
}
return _instance.Get()-> _descriptors[type];
}
private:
DescriptorsMap() {
descriptors[Yellow] = new Descriptor("Yellow", 42, ...);
descriptors[Big] = new Descriptor("InJapan", 17, ...)
...
}
~DescriptorsMap() {
/*Delete all the descriptors from the map*/
}
static autoptr<DescriptorsMap> _instance;
map<InstanceType, Descriptor*> _descriptors;
}
Now we can do this:
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}
virtual void UseClass() { /* do something */ }
};
At the end of execution, when the C runtime performs uninitializations, it also calls the destructor of static objects, including our autoptr, which in deletes our instance of the DescriptorsMap.
So now we have a single instance of each descriptor that is also being deleted at the end of execution.
Note that if the only purpose of the derived class is to supply the relevant "descriptor" data (i.e. as opposed to implementing virtual functions) then you should make do with making the base class non-abstract, and just creating an instance with the appropriate descriptor each time.
I agree with Hershi's suggestion to use a template as the "base class". From what you're describing, it sounds more like a use for templates rather then subclassing.
You could create a template as follows ( have not tried to compile this ):
template <typename T>
class Object
{
public:
Object( const T& newObject ) : yourObject(newObject) {} ;
T GetObject() const { return yourObject } ;
void SetObject( const T& newObject ) { yourObject = newObject } ;
protected:
const T yourObject ;
} ;
class SomeClassOne
{
public:
SomeClassOne( const std::vector& someData )
{
yourData.SetObject( someData ) ;
}
private:
Object<std::vector<int>> yourData ;
} ;
This will let you use the template class methods to modify the data as needed from within your custom classes that use the data and share the various aspects of the template class.
If you're intent on using inheritance, then you might have to resort to the "joys" of using a void* pointer in your BaseClass and dealing with casting, etc.
However, based on your explanation, it seems like you need templates and not inheritance.
#Hershi: the problem with that approach is that each instance of each derived class has a copy of the data, which may be expensive in some way.
Perhaps you could try something like this (I'm spit-balling without a compiling example, but the idea should be clear).
#include <iostream>
#include <string>
using namespace std;
struct DerivedData
{
DerivedData(const string & word, const int number) :
my_word(word), my_number(number) {}
const string my_word;
const int my_number;
};
class Base {
public:
Base() : m_data(0) {}
string getWord() const { return m_data->my_word; }
int getNumber() const { return m_data->my_number; }
protected:
DerivedData * m_data;
};
class Derived : public Base {
public:
Derived() : Base() {
if(Derived::s_data == 0) {
Derived::s_data = new DerivedData("abc", 1);
}
m_data = s_data;
}
private:
static DerivedData * s_data;
};
DerivedData * Derived::s_data = 0;
int main()
{
Base * p_b = new Derived();
cout getWord() << endl;
}
Regarding the follow-up question on deleting the static object: the only solution that comes to mind is to use a smart pointer, something like the Boost shared pointer.
It sounds as if you're trying to avoid having to duplicate the code at the leaf classes, so why not just derive an intermediate base class from the base class. this intermediate class can hold the static data, and have all your leaf classes derive from the intermediate base class. This presupposes that one static piece of data held over all the derived classes is desired, which seems so from your example.