Home > database >  C , using a class that have no constructor
C , using a class that have no constructor

Time:05-27

Assuming I have the following code:

class RecommenderSystemLoader
{

private:

public:
    RecommenderSystemLoader() = delete;

    /**
     * loads movies by the given format for movies with their feature's score
     * @param movies_file_path a path to the file of the movies
     * @return shared pointer to a RecommenderSystem which was created with those movies
     */
    static std::unique_ptr<RecommenderSystem> create_rs_from_movies_file(const std::string& movies_file_path) noexcept(false);
};


Assuming that RecommenderSystem is another class. I was wondering how can I obtain an instance of this class and use the static function create_rs_from_movies_file that lies in it, given the fact there is no constructor at all. I want to do it from the main.cpp file.

CodePudding user response:

Not sure about what you are trying to do, it seems to me you are searching for a creational pattern, maybe factory method design pattern.

However, to directly address your question, if you want to call create_rs_from_movies_file you don't need to have an instance of RecommenderSystemLoader because the method is static.

From a main.cpp you can write:

auto rec_sys = RecommenderSystemLoader::create_rs_from_movies_file(path)

CodePudding user response:

how can I obtain an instance of this class

For your given example you can use zero initialization to create an instance of RecommenderSystemLoader as shown below:

//create an instance 
RecommenderSystemLoader r{};

Working demo


how can i use the static function create_rs_from_movies_file that lies in it

The static member function create_rs_from_movies_file can be called without any object so you don't need to create an instance to use create_rs_from_movies_file.

CodePudding user response:

It's not clear how relevant RecommenderSystem class in your question. Please let me guess what exactly you are trying to achieve. Static functions are part of the class type. You don't need a class instance in order to call static function. Look at the following example. Maybe it will help with refining the question.

class SystemLoaderA {
public:
  static void f() { printf("Hello!\n"); }
};

class SystemLoaderB {
public:
  static void f() { printf("Bye!\n"); }
};

template<typename T>
class D {
  public:
    D() {
      T::f(); // T is type, not an object
    }
};


int main() {
  D<SystemLoaderB> YourD;       // prints Bye!

  using MyD = D<SystemLoaderA>;
  MyD myD; // prints Hello!
}
  • Related