I would like to assert that a base class is only inherited private.
class Base {
static_assert(...); //check if its derived privat
};
class PublicDerived : public Base {}; //this should fail
class PrivateDerived : private Base {}; //this should work
Is there a way to achieve this?
Base can also be a template class.
My problem was that I don't want that the destructor is called from this base class. For example from delete Base* or unique_ptr<Base>.
A protected destructor solves this issue.
Now the derived classes can use these functionalities the base class provides.
Public inheritation is still possible, but my use case is fullfilled.
class Base {
//...
protected:
constexpr Base() noexcept = default;
~Base() noexcept = default;
};
Let's say I have a class like so:
class A
{
public:
template <class T> static inline T* Create()
{
static_assert(std::is_base_of<A, T>::value);
return new T;
}
protected:
A();
virtual ~A();
}
The goal is all objects of classes that derive from "A" to be created only on the heap. This code will work for objects of type A, since the destructor is not public, but nothing stops the creation of an derived class that creates a public destructor.
Is there any way to achieve this?
Quick question. Is there anyway to inherit a singleton so that the child class is a singleton? I have searched around but every singleton I can find is implemented per class, and not in a generic fashion.
Yes there is a generic way. You can implement a Singleton via CRTP, like:
template<typename T>
class Singleton
{
protected:
Singleton() noexcept = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
virtual ~Singleton() = default; // to silence base class Singleton<T> has a
// non-virtual destructor [-Weffc++]
public:
static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
{
// Guaranteed to be destroyed.
// Instantiated on first use.
// Thread safe in C++11
static T instance{};
return instance;
}
};
then derive from it to make your child a Singleton:
class MySingleton: public Singleton<MySingleton>
{
// needs to be friend in order to
// access the private constructor/destructor
friend class Singleton<MySingleton>;
public:
// Declare all public members here
private:
MySingleton()
{
// Implement the constructor here
}
~MySingleton()
{
// Implement the destructor here
}
};
Live on Coliru
A singleton has a static getInstance() method that upon first invocation creates the single instance of the class, and therefore is statically-bound to the type of singleton class being instantiated. I don't see the immediate utility of having a Singleton hierarchy. But if you insist on having one, you might consider making the getInstance method virtual and overriding it in the class extending your parent Singleton.
class Singleton {
public virtual Singleton * getInstance() const
{
// instantiate Singleton if necessary
// return pointer to instance
}
...
};
class MySingleton : public Singleton {
// overrides Singelton's getInstance
public virtual MySingleton * getInstance() const
{
// instantiate MySingleton if necessary
// return pointer to instance
}
};
Of course, a robust implementation would store and return smart pointers.
How can I return the object or call the getInstance of derived class whose base is singleton
You would have to use virtual static method, which is not supported in C++ (It's supported in Delphi, as far as I remember - a curiosity).
You have to decide, whether there's only one instance of both classes or of each class (eg. if you create a Derived instance by GetInstance, should you be able to create Base instance).
There is no way to solve this problem inside these classes, you have to create a class factory. Something like that (I've ommited the singleton implementation to make the idea more clear - obviously you know, how to implement one)
class SingletonFactory
{
template<typename T>
static T * GetInstance()
{
return T.GetInstance();
}
};
class Base
{
friend class SingletonFactory;
private:
static Base * GetInstance()
{
// ...
}
protected:
Base()
{
}
};
class Derived : public Base
{
friend class SingletonFactory;
private:
static Derived * GetInstance()
{
}
protected:
Derived()
: Base()
{
}
};
// (...)
Derived * d = SingletonFactory::GetInstance<Derived>();
I have 6 classes which all perform the same actions. I would like to move common behavior to a common [base] class.
There are actions to be performed on 6 separate objects. The six objects are located in derived classes. Intuitively, the private member objects would be accessed through the child (derived class) in the base class.
What is the C++ pattern I am looking for?
class Base
{
// Common behavior, operate on m_object
...
void Foo()
{
m_object.Bar();
}
};
class Derived1 : public Base
{
// No methods, use Base methods
private:
MyObject1 m_object;
}
class Derived2 : public Base
{
// No methods, use Base methods
private:
MyObject2 m_object;
}
The thing that is boxing me into this situation is MyObject1, MyObject2, etc offer Bar(), but don't share a common base class. I really can't fix the derivation because the objects come from an external library.
If they are introduced in the derived classes, then the base class cannot directly access them. How would the base class know that all derived classes have a specific member?
You could use virtual protected methods like so:
class my_base
{
protected:
virtual int get_whatever();
virtual double get_whatever2();
private:
void process()
{
int y = get_whatever();
double x = get_whatever2();
//yay, profit?
}
}
class my_derived_1 : my_base
{
protected:
virtual int get_whatever()
{
return _my_integer;
}
virtual double get_whatever2()
{
return _my_double;
}
}
Another possibility (if you want to call the base methods from the derived classes) is to simply supply the arguments to the base methods.
class my_base
{
protected:
void handle_whatever(int & arg);
};
class my_derived : my_base
{
void do()
{
my_base::handle_whatever(member);
}
int member;
};
C++ does and doesn't. It has a very powerful multiple inheritance support, so there is no super keyword. Why? Imagine that your base class is, say, inherited by another two classes, or even is a part of virtual inheritance hierarchy. In that case you can't really tell what super is supposed to mean. On the other hand, there are virtual methods, you can always have them in base class and implement in derived classes (that's what languages like Java do, except that they they don't have multiple class inheritance support). If you don't want to go with polymorphism, you can use something like this:
#include <cstdio>
template <typename T>
struct Base
{
void foo ()
{
std::printf ("Base::foo\n");
static_cast<T *> (this)->bar ();
}
};
struct Derived : Base<Derived>
{
void bar ()
{
std::printf ("Derived::bar\n");
}
};
int
main ()
{
Derived d;
d.foo ();
}
This is an extremely simple example - you can extend the above example with access control, friends, compile-time assertions etcetera, but you get the idea.
Have you considered not using inheritance?
class FooBar
{
MyObject m_object;
public:
FooBar(MyObject m): m_object(m) {}
//operate on different m_objects all you want
};
What about deriving your six separate objects from a common base class? Then you can declare virtual methods in that base class to create your interface, and then implement them in the derived object classes.
Maybe you just need a template instead of superclass and 6 derived classes?
It seems that you need to access not the parent's, but child's field. You should do it by introducing an abstract method:
class ParentClass
{
public:
void f();
protected:
virtual int getSomething() = 0;
};
ParentClass::f()
{
cout << getSomething() << endl;
}
class DerivedClass : public ParentClass
{
protected:
virtual int getSomething();
}
DerivedClass::getSomething() { return 42; }
If you need to access parent's method, just use ParentClass::method(...):
class ParentClass
{
public:
virtual void f();
};
class DerivedClass : public ParentClass
{
public:
virtual void f();
};
void DerivedClass::f()
{
ParentClass::f();
}