Shilaly
Shilaly

Reputation: 23

Cannot call member function std::string class::function() without object

I know it may seem like this has been asked before but I've looked around and the static method didn't work for me. Here's my code:

struct Customer {
public:
    string get_name();
private:
    string customer,first, last;
};

Here's where I call the function:

void creation::new_account() {
Customer::get_name(); //line it gives the error on.
}

Here's an example of some code that compiles fine.

struct Creation { public: string get_date(); private: string date; };

then I call it the same way

void Creation::new_account() { Creation::get_date();}

Hence my confusion why one works and the other doesn't.

EDIT: Ok I get it, I just realized I was calling a function of another struct inside a function definition that's part of a different class. I got it, thanks to all who answered

Upvotes: 0

Views: 2189

Answers (3)

hmjd
hmjd

Reputation: 121971

It is not declared static (needs to be static std::string get_name();). However, get_name() for Customer is a specific attribute of a Customer instance so having it static does not make sense, that is the same name for all instances of Customer. Declare an object of Customer and use it. It would make sense to have the name provided to the constructor of Customer, as surely a customer cannot exist without a name:

class Customer {
public:
    Customer(std::string a_first_name,
             std::string a_last_name) : first_name_(std::move(a_first_name)),
                                        last_name_(std::move(a_last_name)) {}
    std::string get_name();
private:
    std::string first_name_;
    std::string last_name_;
};

Declare an instance of Customer:

Customer c("stack", "overflow");
std::cout << c.get_name() << "\n";

Upvotes: 1

JBL
JBL

Reputation: 12907

"The static method didn't work for me". It's not a method it's how the language works.

If you want to call some method without a concrete object, you need it to be static. Otherwise, you need an object.

Your code will work with one of the following :

struct Customer {
public:
    static string get_name();
private:
    string customer,first, last;
};

or

void creation::new_account() {
    Customer c;
    //stuff
    c.get_name();
}

Upvotes: 0

Since your get_name is not declared static, it is a member function.

You probably need some constructors in your Customer class. Assuming you have some, you could code

 Customer cust1("foo123","John","Doe");
 string name1 = cust1.get_name();

You need an object (here cust1) to call its get_name member function (or method).

Time to spend many hours reading a good C++ programming book.

Upvotes: 0

Related Questions