-1
using namespace std;

class PersonA{
    private:
    PersonA(){cout << "PersonA cconstr called" << endl;};

    public:
    PersonA* createInstance(){
        cout << "Instance created" << endl;
        return new PersonA;
    };
};

int main()
{
    PersonA* Hello = PersonA::createInstance();
    return 0;
}

My IDE is giving me an error which says: Call to non static member function without an argument I dont understand why this method requires an argument? Am i missing something?

LuckyBlue
  • 7
  • 4

2 Answers2

1

you can do it like -

#include <iostream>

using namespace std;

class PersonA{
    private:
    PersonA(){cout << "PersonA cconstr called" << endl;};
    static PersonA* p;
    public:
    static PersonA* createInstance(){
        if(p == nullptr)
        {
            cout << "Instance created" << endl;
            p= new PersonA();
        }
        return p;
    };
};

PersonA* PersonA::p=nullptr;

int main()
{
    PersonA* A = PersonA::createInstance();
    PersonA* B = PersonA::createInstance();
    return 0;
}
user1438832
  • 493
  • 3
  • 10
1

static is missing.

but you don't implement singleton pattern currently, if you want to, use Meyers' one:

class PersonA
{
private:
    PersonA() { std::cout << "PersonA constr called" << std::endl;}
public:
    PersonA(const PersonA&) = delete;
    PersonA& operator =(const PersonA&) = delete;

    static PersonA& getInstance(){
        static PersonA instance{};
        return instance;
    }
};

But maybe you just want a factory method, then avoid raw owning pointer, and use smart pointer:

class PersonA{
private:
    PersonA() { std::cout << "PersonA constr called" << std::endl;}

public:
    std::unique_ptr<PersonA> create()
    {
        std::cout << "Instance created" << std::endl;
        return std::make_unique<PersonA>();
    }
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302