-1

I was trying to develop an executable which has standard functionality at product level and additional custom functionality at solution level.

I wrote class A at product level and class B derived from class A at solution level. There is an Init() function at both levels and I want to call the Init() function of class B if executable is built from solution level. Also note main function resides in product level.

My code is listed below;


PRODUCT LEVEL


A.h at product level

#include <iostream>

#define App A::GetInstance()

class A
{
public:
    A(int priority = 1);
    virtual ~A(){}
    virtual void Init() { printf("Called Class A function \n"); }

    static A& GetInstance() { return *_instance;}

private:

    static A* _instance;
    static int _priority;
};

A.cpp at product level

#include "A.h"

A* A::_instance = new A();
int A::_priority = 0;

A::A(int priority)
{
    if (priority > _priority)
    {
        _instance = this; 
        _priority = priority;   
    } 
}

main.cpp at product level

#include "A.h"

int main(int argc, char** argv)
{

    App.Init();

    return 0;
}

SOLUTION LEVEL


B.h at solution level

#include "A.h"

class B : public A
{
public:
    B(int priority = 2);
    virtual ~B(){}
    virtual void Init() { printf("Called Class B function \n"); }
};

B.cpp at solution level

#include "B.h"

B* b = new B();

B::B(int priority):A(priority)
{ 

}

My questions are?

  1. Instead of global objects is there a better approach to this?
  2. Also if I change the make order of the object files then different output is produced with the same code? is there a way to overcome this?

    a.) g++ -o test A.cpp B.cpp main.cpp

    ./test ------- >outputs ----> Called Class A function

    b.) g++ -o test B.cpp A.cpp main.cpp

    ./test ------- >outputs ----> Called Class B function

  3. Is my implementation is the ideal method for n number of levels? (e.g. solutions that build from another solution)

Gayan Pathirage
  • 1,979
  • 1
  • 24
  • 21

1 Answers1

0

This line need to be change as this;

from

A* A::_instance = new A();

To

A* A::_instance;
A* a = new A();

When you assign new instance to A::_instance using

A* A::_instance = new A();

it overwrite the value assigned by the B's constructor. So you can avoid it by removing the direct assignment to _instance. The constructor will do that.

Supun Induwara
  • 1,594
  • 3
  • 14
  • 22