Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an instance of a class within the same class?

Tags:

c++

c++11

Say I have a class:

class Foo{
public:

    Foo(){
    }

    //Is it possible to create a function like this:
    virtual Foo* createOb(){
       //Should create a new Foo,Bar or Fiz, depending on the actual object type.
    }
}

class Bar: public Foo{
public:

    Bar(){
    }
}

class Fiz: public Foo{
public:

    Fiz(){
    }
}

Is it possible to have a method createOb() in the base class, so when createOb() is called on an instance of one of the derived classes, that an instance of the derived class is created ?

like image 589
Rahul Iyer Avatar asked Aug 30 '16 10:08

Rahul Iyer


People also ask

Can you make an instance of a class in itself?

Yes, you can, but it's relatively less common for you to want to. In a method like showLine() , which is an instance method, your code is already executing in the context of a Second_Example instance.

How do you create an instance of a class within another class in Java?

Inner classesTo instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass. InnerClass innerObject = outerObject.

Can you create an object of a class within the same class C++?

A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type.

Can we create object of a class inside the same class python?

After it is created, you can add it back to the class with Employee. obj1 = obj1 . The reason for the extra step is that normally just can't create an instance of a class inside the class definition. Otherwise, you're calling a class that hasn't been defined yet.


Video Answer


1 Answers

Yes, it can be done, using CRTP.

Bu first, returning a raw pointer obtained from new is very dangerous. In c++ raw pointers should be used only when they do not have ownership of the pointed object. So I took the liberty to use unique_ptr:

struct Base {
  virtual auto create_obj() -> std::unique_ptr<Base>
  {
    return std::unique_ptr<Base>{};
  }
};

// abstract works too:
struct Base {
  virtual auto create_obj() -> std::unique_ptr<Base> = 0;
};

template <class Derived>
struct Base_crtp : Base {
  auto create_obj() -> std::unique_ptr<Base> override /* final */
  {
    return std::unique_ptr<Base>{new Derived{}};
  }
};

struct D1 : Base_crtp<D1>
{
};

struct D2 : Base_crtp<D2>
{
};

And then:

auto b1 = std::unique_ptr<Base>{new D1{}};
auto b2 = std::unique_ptr<Base>{new D2{}};

auto new_d1 = b1->create_obj();
auto new_d2 = b2->create_obj();
like image 89
bolov Avatar answered Oct 10 '22 14:10

bolov