views:

82

answers:

2

Hi all, i'm developing a c++ dll that containts three classes: say base class Base, Derived1 and Derived2 class. The scenario:

class Base { //ctor, dtor, members and methods here }

class Derived1 : public Base { //ctor, dtor, members and methods here }

class Derived2 : public Base { //ctor, dtor, members and methods here }

The dll i'm creating with MS VC++ 2008 express, that i want use under Turboc++ (borland: very good ide/rad). I export Derived1 via facotry method, and via client code, Derived1 makes instances of Derived2. Both Derived1 and Derived2 share a pointer function contained in another dll, so i put that poiner function under Base class. Here is the problem. Once time i create one instance (via factory) of Derived1 and it can create multiple instances of Derived2, so Base class CTOR is called more times (1 for Derived1 and multiple times for Derived2). How can i prevent multiple intances of Base?

A further question:

With the scenario i described early, Derived1 call multiple intances of Derived2 and both Derived1 and Derievd2 extends unique common base class. I ask: it is a bad design? is there another design of classes and their inheritance hierarchy better than i used?

+1  A: 

You can't prevent multiple instances of Base. You can prevent multiple instances of the pointer - make it static:

class Base {
    public:
        // save first pointer I get passed
        Base( sometype * p ) {
            if ( myptr == 0 ) {
               myptr = p;
            }
        }

    private:

       static sometype * myptr;
};

In a C++ source file you will need to define myptr:

sometype * Base::myptr = 0;
anon
Since every instance of Derived* is to the Base::Base() ctor an instance of Base, you can't really prevent multiple instances of Base, because you absolutely need them. Neil is absolutely right about making the functionPtr static to solve your problem.
AndreasT
A: 

Ok, tank you for very very quick reply. I have other question: with the scenario i described early, Derived1 call multiple intances of Derived2 and both Derived1 and Derievd2 extends unique common base class. I ask: it is a bad design? is there another design of classes and their inheritance hierarchy better than i used?