How to call the overriden function in the singleton - c++

I am new to C++ and recently I have a problem of calling an overriden function from a singleton, the example code is:
class ParentClass
{
public:
ParentClass(){};
~ParentClass(){};
private:
static ParentClass * mInstance;
virtual methodA()
{
//...
}
};
ParentClass * ParentClass::mInstance = new ParentClass;
class ChildClass : public ParentClass
{
private:
virtual methodA() override
{
//....
};
}
Is there anyway to call the overriden methodA for the mInstance?

Change from ParentClass * ParentClass::mInstance = new ParentClass; to ParentClass * ParentClass::mInstance = new ChildClass; You need to instantiate the child class that overrides the function.
Otherwise, no, with the given mInstance (as instance of ParentClass) there is no way of calling the overriden function

Make this following change:
ParentClass * ParentClass::mInstance = new ChildClass;
Otherwise you will not be able to call overriden methodA.

No. You can't polymorphically call an overriden function that is marked private in the base class. A private function can only be called by the owning class itself. If you want a class' function to be exclusively visible to its derived children, then mark it as protected.
And your class ParentClass is not a singleton. A singleton class can't have a public constructor as there must only be one static instance. Ever.
It would also seem meaningless to inherit from a singleton class as the derived class, like its base, can never be constructed during runtime (unless the base's ctor is protected, but then it is starting to smell). All it can do is to access static members of the base or itself.
Anyway, the idiomatic C++-singleton class looks like this:
class singleton {
public:
singleton(const singleton&) = delete;
singleton& operator=(const singleton&) = delete;
static singleton& get_instance() {
static singleton instance;
return instance;
}
private:
singleton() {}
};

Related

Overriding linking in Cpp to point to mocked implementation

I need to mock some classes using GoogleMock and change the base class implementation so that it creates actually an instance of this mocked one.
The base class is generated automatically along with some other classes that don't need to be mocked and all added in the same library.
The classes that need to be mocked are created through a factory, through which i intend to return the child class.
Can i "relink" with this new library which has implementation for already linked base class?
What i hope to achieve is get the instance of the base class from the unit-under-test and then cast it up to the mocked one.
Code example:
Original.hpp
class Base
{
private:
Base();
public:
virtual ~Base();
static std::shared_ptr<Base> createInstance();
}
Original.cpp
#include "Original.hpp"
...
std::shared_ptr<Base> Base::createInstance()
{
return std::shared_ptr<Base>(new Base());
}
...
Modified.hpp
class Derived : public Base
.....
Modified.cpp
#include "Original.hpp"
#include "Modified.hpp"
...
std::shared_ptr<Base> Base::createInstance()
{
return std::shared_ptr<Base>((Base*) new Derived());
}
So i want whenever the Base class is instantiated through createInstance anywhere in the project, the createInstance defined in Modified.cpp to be used instead, to return the Derived class.
OK, I think I understand more or less. If the library is already compiled you cannot change the implementation of that static factory method. If you provide your own implementation and try to link it with the existing lib you will have multiple definition (not allowed). What you can do is to add one layer to your application that will be responsible for this Base objects creation:
// existing implementation
class Base {
public:
virtual ~Base();
static std::shared_ptr<Base> createInstance() {
return std::shared_ptr<Base>(new Base());
}
private:
Base() {};
};
// new layer, part of your production code
class IYourFactory {
public:
virtual ~IYourFactory() = default;
virtual std::shared_ptr<Base> createInstance() = 0;
};
// new layer, part of your production code
class ProductionFactory: public IYourFactory {
public:
~ProductionFactory() override = default;
std::shared_ptr<Base> createInstance() override {
return Base::createInstance();
}
};
// testing code, you can use GMock to create this class
class MockBase: public Base {
public:
// it's a hack for Base private default constructor
MockBase(): Base(*Base::createInstance()) {}
~MockBase() override = default;
};
// testing code, you can use GMock to create this class
class MockFactory: public IYourFactory {
~MockFactory() override = default;
std::shared_ptr<Base> createInstance() override {
return std::make_shared<MockBase>();
}
};
class YourSystem {
public:
YourSystem(std::shared_ptr<IYourFactory> factory): factory_(factory) {}
bool doSomeThings() {
auto basePtr = factory_->createInstance();
return true;
}
private:
std::shared_ptr<IYourFactory> factory_;
};
Of course it will only do the job if Base class has some virtual functions that you can override in your MockBase. If not, this is not the way to go (you will need to create your own interface for the methods offered by Base).
The exact solution depends on how you use it in your system and what is the interface to Base.

How to call a method of derived class from a method of base class without making it virtual?

How would I do so without making base method virtual?
class Base {
public:
bool foo() const;
}
class Derived : public Base{
public:
bool foo() const;
}
There is no any sense to call isEmpty of a derived class from isEmpty of the base class because the base class knows nothing about its derived classes. Take into account that the base class is single while there can be numerous derived classes. So of what derived class are you going to call function isEmpty?
There is sense to call isEmpty of the base class in a derived class. it can be done the following way
bool Derived::isEmpty() const
{
return Base::isEmpty();
}
You cannot. That's why there is a virtual keyword. If your class forbids use of this keyword, I'd rather not use it as a starting point to learn OOP.
If you really need this, you can store a null pointer to a function with the foo's signature in your base class instances, and use the base implementation until this pointer is null. Then you can change this pointer in your derived class and associate is with your derived implementation. Then your base class can call that function via the pointer.
Below is some schematic code for this:
class Base {
public:
bool foo() const {
if (NULL == internalFoo) {
// base implementation;
} else {
return internalFoo();
}
}
private:
bool (*internalFoo)() = NULL;
}
class Derived : public Base{
public:
bool foo() const;
}

Perform operations BEFORE calling destructor in C++ QObject subclass

I have a class hierarchy which inherits QObject.
I need to perform some operations after construction (when the object is fully constructed) and before destruction (when the object is still complete).
The construction part is no problem, since I can control the construction of an object, making private its constructor and just making public the creator function which already can perform all the required operations.
The problem comes with the destructor. I have done more or less the same: hiding the destructor and providing a destroyer function which performs all the operations and then destroys the object.
Here is where the problem begins:my class hierarchy is used as part of the QJSEngine scripting module, which takes ownership of all the objects, and when it is time, it destroys them using the QObject's destructor, thus, bypassing my destroyer function. It is of no help declaring my destructors private, since the QJSEngine can always execute the QObject's destructor (and by the way, also can any piece of code which casts my pointers to QObject).
I require to perform this operations before calling the destructor, since I use some virtual functions, so I need to execute this BEFORE beginning the destruction process, so the virtual functions calls will not fail.
Is there a way to achieve this?
I attach a basic code snipped showing my problem:
class IBase: public QObject {
public:
template<typename T>
static IBase * create() {
IBase * obj=new T;
obj->afterConstruction();
return obj;
}
void destroy() {
this->beforeDestruction();
delete this;
}
protected:
IBase(): fBeforeDestruction(false){}
virtual ~IBase(){
//Try to perform operations, but it is too late....
if (!fBeforeDestruction)
doBeforeDestruction();
}
virtual void doAfterConstruction(){}
virtual void doBeforeDestruction(){}
private:
bool fBeforeDestruction;
void afterConstruction() {
doAfterConstruction();
}
void beforeDestruction(){
fBeforeDestruction=true;
doBeforeDestruction();
}
};
class TSubclass: public IBase {
protected:
TSubclass(){}
virtual ~TSubclass(){}
virtual void doAfterConstruction(){
qDebug()<<"AfterConstruction";
}
virtual void doBeforeDestruction(){
qDebug()<<"BeforeDestruction";
}
private:
friend class IBase;
};
int main(int argc, char *argv[])
{
//QObject *obj=new TSubclass() //Compile time error! Nice!
QObject *obj=IBase::create<TSubclass>();
delete obj;//Wrong! BeforeDestruction is NEVER shown!!! <---- How to change this behaviour?
IBase * obj2=IBase::create<TSubclass>();
//delete obj2; //Compile time error! Nice!
obj2->destroy(); //Nice!
}
EDIT:
After some comments, I have to add to the question that I want to do several operations before the destructor for two reasons:
Virtual calls: The virtual calls are not allowed inside the destructor, since they will not call the overriden functions, but only the functions in the current destroying class.
Dynamic casts downcasting: Some of the things to do involve donwcasting via dynamic_cast. dynamic_cast downcasting inside the destructors always fails.
EDIT 2:
The answer of Ezee works as I needed. Here is my complete code snippet, showing the code, with also a dynamic_cast:
template <typename T>
class TAfterConstructionBeforeDestruction: public T {
public:
~TAfterConstructionBeforeDestruction() {
this->beforeDestruction();
}
protected:
using T::T;
};
class IBase: public QObject {
public:
//Now it can be public, just as the one in QObject!
virtual ~IBase(){}
template<typename T>
static IBase * create() {
//Create a
IBase * obj=new TAfterConstructionBeforeDestruction<T>;
obj->afterConstruction();
return obj;
}
protected:
IBase(){}
virtual void afterConstruction(){}
virtual void beforeDestruction(){}
};
class TSubclass: public IBase {
public:
virtual ~TSubclass(){}
protected:
TSubclass(){}
virtual void afterConstruction(){
qDebug()<<"AfterConstruction";
}
virtual void beforeDestruction();
private:
friend class IBase;
};
class TSubclass2: public TSubclass {
public:
virtual ~TSubclass2(){}
protected:
TSubclass2(){}
virtual void beforeDestruction(){
qDebug()<<"BeforeDestruction from Subclass2";
TSubclass::beforeDestruction();
}
};
void TSubclass::beforeDestruction() {
qDebug()<<"BeforeDestruction";
TSubclass2 * sub=dynamic_cast<TSubclass2*>(this);
if (sub) {
qDebug()<<"We are actually a TSubclass2!";
}
}
int main(int argc, char *argv[])
{
//QObject *obj=new TSubclass() //Compile time error! Nice!
QObject *obj=IBase::create<TSubclass>();
delete obj;//Now it works fine!
IBase * obj2=IBase::create<TSubclass2>();
delete obj2; //It is still succeeding to dynamic_cast to TSubclass2 without any problem!
}
First of all, I must say that calling virtual methods from a constructor or a destructor is a very bad practice.
Call doAfterConstruction() from the constructor of the mose derived descendant of IBase.
Call doBeforeDestruction() from the destructor of the mose derived descendant of IBase.
You can do the same using signals/slots:
Declare a signal beforeDestroyed() in IBase (add Q_OBJECT macro also).
In the constructor of IBase connect this signal to a slot doBeforeDestruction (make it a slot).
In the destructor of the mose derived descendant of IBase emit the signal: emit beforeDestroyed().
If you have a lot of descendants you may want to avoid doing the same thing in every constructor/destructor. In this case you can use a template also:
template <class T>
class FirstAndLastCall : public T
{
public:
FirstAndLastCall ()
{
doAfterConstruction();
}
~FirstAndLastCall
{
doBeforeDestruction();
}
}
Usage:
IBase* obj2 = new FirstAndLastCall<TSubclass>();

Is this standard way to derive from singleton class?

My Base class is Singleton having protected c'tor. Now, I can derive another class from it but I cannot create instance of that Base class inside functions of derived class. This is expected behavior as per my design. But I like to know is it correct by C++ standards or just my compiler specific behavior? (So that I shouldn't face issues if I want to port this code in future)
class Singleton
{
protected:
Singleton() {}
public:
Singleton * GetInstance()
{
static Singleton* InstanceCreated = NULL ;
if (!InstanceCreated)
InstanceCreated = new Singleton ;
return InstanceCreated ;
}
};
class Deringlton : public Singleton
{
public:
Deringlton()
{
Singleton * pSing ;
// pSing = new Singlton ; // Cannot create object of singlton
// (Despite class is derived from singlton)
}
};
I think a better way to provide a generic singleton implementation is to use the CRTP and directly inheriting from that template. That means every class automagically implements the singleton pattern only inheriting from the CRTP base:
template<typename DERIVED>
class generic_singleton
{
private:
static DERIVED* _instance;
static void _singleton_deleter() { delete _instance; } //Function that manages the destruction of the instance at the end of the execution.
protected:
generic_singleton() {}
virtual ~generic_singleton() {} //IMPORTANT: virtual destructor
public:
DERIVED& instance() //Never return pointers!!! Be aware of "delete Foo.instance()"
{
if(!_instance)
{
_instance = new DERIVED;
std::atexit( _singleton_deleter ); //Destruction of instance registered at runtime exit (No leak).
}
return static_cast<DERIVED&>( _instance );
}
};
template<typename DERIVED>
DERIVED* generic_singleton<DERIVED>::_instance = nullptr;
The memory release is provided by registering a function that does the delete at the end of the application, with std::ateexit().
What's the point of having a pointer an not just a static variable?
class Singleton
{
public:
static Singleton& instance()
{ static Singleton z; return z; }
private:
Singleton() {}
~SIngleton() {}
};
In don't see any value in deriving it.
If you want to make this pattern coded as a template you can do
template<class S>
S& instance_of() { static S z; return z; }
and make instance_of<yourclass>() a friend of yourclass, having private ctor / dtor.
The use of a static variable makes the object granted to be properly constructed and destructed. (Unlike a remaining leaked pointer, with no destructor call...)
If you have to make a singleton (which you should avoid) the instance and(!) the declaration are a singleton. You could use a template have a 'generic' one, but inheritance is no good.
This is expected behaviour. The rule is you can only access protected members in Deringlton if the pointer is of type Deringlton. You cannot access protected members through a pointer of type Singleton. For example:
Deringlton* d = this;
d->someProtectedMethod(); // OK!
Singleton* s = this;
s->someProtectedMethod(); // Will fail
Since accessing new Singleton is not through a Deringlton pointer, it is not allowed. You can only access it through Deringlton by doing new Deringlton.
This behavior is specified in the standard.
Section 11.4 [class.protected] of C++11 states (emphasis mine):
As described earlier, access to a protected member is granted because
the reference occurs in a friend or member of some class C. If the
access is to form a pointer to member (5.3.1), the
nested-name-specifier shall denote C or a class derived from C. All
other accesses involve a (possibly implicit) object expression
(5.2.5). In this case, the class of the object expression shall be C
or a class derived from C.
What this means is that access to the base constructor is granted only if you are creating an object of the derived class. So for example, this would compile:
Deringlton()
{
Deringlton* p = new Deringlton();
}

Invoke abstract method in super class, and implement it in subclass in C++?

In Java it's possible to write an abstract, super class with unimplemented, abstract methods and non-abstract methods which invoke the abstract methods. Then in the subclass are the abstract methods implemented. When you then make an instance of the subclass, the super class uses the implementations in the subclass. How do I accomplish this in C++?
Here is what I mean, but in Java:
SuperClass.java
public abstract class SuperClass {
public SuperClass() {
method();
}
private void method() {
unimplementedMethod();
}
protected abstract void unimplementedMethod();
}
SubClass.java
public class SubClass extends SuperClass {
public SubClass() {
super();
}
#Override
protected void unimplementedMethod() {
System.out.println("print");
}
public static void main(String[] args) {
new SubClass();
}
}
Would be awesome if you showed me how this is accomplished in C++. :)
In general, what you are looking for, is the virtual keyword. In a nutshell virtual declares the intent that this method can be overriden. Note that such a method can still have an implementation- virtual just makes it overrideable. To declare an "abstract method", you can say declare intent of please provide an implementation in the derived class with = 0, as shown below. Such methods are called pure virtual in C++.
However, there are some caveats that you should watch out for. As pointed out in a comment below, you were calling method() from within the SuperClass constructor. Unfortunately this is not possible in C++, due to the order in which objects are constructed.
In C++ a derived class constructor immediately calls it's superclass constructor before allocating its members or executing the body of the constructor. As such, the members of the base class are constructed first, and the derived class' members are constructed last. Calling a virtual method from a base class will not work as you expect in Java, since the derived class has not been constructed yet, and thus the virtual methods have not been redirected to the derived implementations yet. Hope that makes sense.
However, calling method() on a SuperClass object after creation will work as you expect: it would call the virtual function which would output "print".
class SuperClass {
public:
SuperClass() {
// cannot call virtual functions from base constructor.
}
virtual ~SuperClass() { } // destructor. as Kerrek mentions,
// classes that will be inherited from,
// should always have virtual destructors.
// This allows the destructors of derived classes
// to be called when the base is destroyed.
private:
void method() {
unimplementedMethod();
}
protected:
virtual void unimplementedMethod() = 0; // makes method pure virtual,
// to be implemented in subclass
}
SubClass.h
class SubClass : public SuperClass {
public:
SubClass() : SuperClass() { // how the superclass constructor is called.
}
// no need for "override" keyword, if the methd has the same name, it will
// automatically override that method from the superclass
protected:
void unimplementedMethod() {
std::cout << "print" << std::endl;
}
}
In C++, you should never call virtual functions in the constructor, so it doesn't work quite as literally. Best to use a separate member function
class SuperClass
{
public:
void action() { method(); } // not in the constructor, please
virtual ~SuperClass() { } // always a virtual destructor when polymorphic
protected:
void method() { unimplementedMethod(); }
private:
virtual void unimplementedMethod() = 0;
};
class SubClass : public SuperClass
{
private:
virtual void unimplementedMethod() { std::cout << "print" << std::endl; }
// no need to spell out the next couple of functions, but for your entertainment only
public:
SubClass() : SuperClass() { }
virtual ~SubClass() { }
};
Now to invoke:
int main()
{
SuperClass * p = new SubClass; // construct first...
p->action(); // ... then invoke, after construction is complete
delete p; // thank god for that virtual destructor!
}
The base constructor runs before the derived class is constructed, so you cannot call any derived functions in the base constructor, and in particular you cannot call any pure-virtual functions.
Note that you have the private and protected the wrong way round: The non-virtual accessor function should be protected so it can be used in the entire class hierarchy, but the virtual implementation function should be private, since it only needs to be seen by the accessor function in the same class. In a nutshell: protected-nonvirtual and private-virtuals.
(The usage example is a bit contrived, since you wouldn't normally use new or raw pointers in C++.)
In C++ these are called pure virtual functions/methods.
Basically you tack a "=0" at the end of a method:
virtual doSomething() = 0; // pure virtual
Search around SO for "c++ pure virtual" and you'll find tons of answers.
You need to use virtual methods. The implementation works like this:
/* here's MyBaseClass.h */
class MyBaseClass
{
public:
MyBaseClass(void);
~MyBaseClass(void);
void MyMethod();
protected:
virtual void MyUnimplementedMethod() = 0;
};
/* here's MyIneritedClass.h */
class MyInheritedClass :
public MyBaseClass
{
public:
MyInheritedClass(void);
~MyInheritedClass(void);
protected:
virtual void MyUnimplementedMethod();
};
/* here's the implementation of the method in the base class */
void MyBaseClass::MyMethod()
{
MyUnimplementedMethod();
}
/* and here's the implementation of the abstract method in the derived */
void MyInheritedClass::MyUnimplementedMethod()
{
_tprintf(L"Hello, world");
}
You declare the method as virtual:
snippet:
class Parent{
public:
virtual int methodA() {return methodB();}; // calls the abstract method
virtual int methodB() = 0; // "=0" means pure virtual, not implemented in the base
}
class Child : public Parent{
public:
virtual int methodB() { /* implementation */}
}
virtual means the child may override the implementation and the parent should be then calling the overriden implementation. Adding "=0" to the declaration of the virtual method makes it pure virtual, i.e.: the base doesn't have an implementation of its own, and relies on the implementation by the child. Such class cannot be instantiated (i.e.: abstract class).