0

I'm trying to put together and understand Singleton design pattern in c++. For some reason I am receiving error. and maybe someone might be able to help and explain what is happening.

#include <iostream>
#include <string>

class Car{
  public:
    static Car* getInstance(){
      instance = new Car;
      return instance;
    }
  private:
    Car(){
      std::cout<<"we made car object\n";
    }
    Car(const Car&);
    static Car *instance;
};

int main(){
  Car test;
  return 0;
}

so when i try compiling this code I am getting an error when trying to create a Car object in my main class: error: 'Car ::Car()' is private within this context.

i am compiling using g++ -std=c++14

piles fun
  • 11
  • 1
  • 2
    If you're making a singleton you don't want to be able to create a `Car` object, you want to use the `getInstance` function to access the singleton variable. [C++ Singleton design pattern](https://stackoverflow.com/questions/1008019/c-singleton-design-pattern) is worth a read. – Retired Ninja Oct 10 '21 at 23:03
  • Well, you shouldn't _be_ creating a `Car` object, you're supposed to just be calling the `getInstance` method to get the single `Car` object that already exists. But your `getInstance` method is more like a factory--it creates a new and distinct `Car` every time you call it. You might take a look at [this answer](https://stackoverflow.com/a/1008289/12334309) that lays out a pretty good pattern for a singleton class, and you may also want to ask yourself "Do I really _need_ a singleton?" – Nathan Pierson Oct 10 '21 at 23:03
  • I can't hammer that dupe. It's a MUCH better way to do a singleton most of the time, but I don't think "throw out what you've done and to this instead is appropriate when it looks like asker's problem is, as Retired Ninja pointed out, invoking the constructor when they should be calling `getInstance`. They'll have the exact same problem with a Meyers' singleton. – user4581301 Oct 11 '21 at 00:21
  • Thanks for all the advice! you guys really helped. I decided to look back and watch some more videos on the topic to better understand when to use it now I am faced with a new problem with my code by getting close. – piles fun Oct 11 '21 at 03:50

0 Answers0