Creating objects from the base class

An attempt to create a driver type class, where below Base is the driver to which the type is passed when the instance is created. Type, 2 in this case, is used to construct the correct derived object.

My compiler throws a syntax declaration error in the "Base Base" line.

My ultimate goal is to do:

Base *B;

    B = new Base(2);
    if(B)
    {
      B->DoStuff();
      B->DoMoreStuff();
      delete B;
    }

Here is my code that will not compile ...

class Base
{
public:

    Base(int h);
    virtual ~Base();

private:
    int hType;
    Base *hHandle;
};


class Derived1 : public Base
{
public:
    Derived1();
    virtual ~Derived1();

};

class Derived2 : public Base
{
public:
    Derived2();
    virtual ~Derived2();

};

Base::Base(int h)
{
    hType = h;

    switch(h)
    {
        case 1:
            hHandle = new Derived1;
        break;

        case 2:
            hHandle = new Derived2;
        break;

    }
}


Derived1::Derived1():Base(1)
{
    printf("\nDerived1 Initialized\n\n");
}

Derived2::Derived2():Base(2)
{
    printf("\nDerived2 Initialized\n\n");
}

Below is the updated code to show the full source. I think now I understand why it will not compile. As indicated below, I have an infinite loop of calls to "new"

#include <stdio.h>

class Base
{
public:

    Base();
    Base(int h);
    Create (int h);
    virtual ~Base();

private:
    int hType;
    Base *hHandle;
};


class Derived1 : public Base
{
public:
    Derived1();
    virtual ~Derived1();

};

class Derived2 : public Base
{
public:
    Derived2();
    virtual ~Derived2();

};

Base::Base()
{

}

Base::Base(int h)
{
    Create(h);
}

Base::Create(int h)
{
    hType = h;

    switch(h)
    {
        case 1:
            hHandle = new Derived1;
        break;

        case 2:
            hHandle = new Derived2;
        break;

    }
}

Derived1::Derived1()
{
    printf("\nDerived1 Initialized\n\n");
}

Derived2::Derived2()
{
    printf("\nDerived2 Initialized\n\n");
}
+5
source share
1 answer

It looks like you are trying to make a factory class .

, Base, Derived1 Derived2.

class Base
{
public:
    static Base* Create(int);
    virtual void DoStuff() = 0;
}

class Derived1 : public Base
{
    Derived1()
    {
        printf("\nDerived1 Initialized\n\n");
    }

    virtual void DoStuff()
    {
    }   
}

class Derived2 : public Base
{
    Derived2()
    {
        printf("\nDerived2 Initialized\n\n");
    }

    virtual void DoStuff()
    {
    }   
}

Base* Base::Create(int n)
{
    if (n==1)
        return new Derived1();
    else if (n==2)
        return new Derived2();
    else
        return nullptr;
}

void main()
{
    Base* B = Base::Create(2);
    if(B)
    {
        B->DoStuff();
        delete B;
    }
}
+2

All Articles