Noam Yagudaev
Noam Yagudaev

Reputation: 65

Expression must have class type. Don't know how to solve

I'm new to the cpp language and I have a problem with my code which I don't know how to solve, I looked here on some other questions people asked about this error, but none of the answers really helped me to solve the problem. So this is my main function:

#include <iostream>
#include "Person.h"
#include <string> 


int main() {
    Person p2();
    Person p1();
    std::cout << p1.toString() << std::endl;
    return 0;
}

and here is my Person.h file:

#ifndef PERSON_H_
#define PERSON_H_
#include <string>
class Person {
private:
    int age;
    std::string name;
    int numOfKids;
public:
    Person() {
        this->age = 0;
        this->name = "bob";
        this->numOfKids = 5;
    }
    Person(int agee, std::string namee, int numof);
    ~Person();
    std::string toString();


};

#endif // PERSON_H_

In the main function it marks p1.toString() and says "expression must have class type" and I don't know what to do, I tried many things and none of them worked.

Upvotes: 2

Views: 874

Answers (2)

Terry Wu
Terry Wu

Reputation: 178

These kind of statement you write can have ambigous meaning: Person p2();

  1. (what you want) a variable p2 with type Person and default constructed.
  2. (the compiler thought) a function declaration p2 returning an object of Persion.

Remove the bracket or using the '{}' (c++11) should make things clear:

Person p1{};
Person p2;

Upvotes: 1

Pedro Isaaco
Pedro Isaaco

Reputation: 404

Various points to correct:

Person(int agee, std::string namee, int numof);
~Person();
std::string toString();

These three are only declared, not defined. This will result in unresolved external symbol error messages from the compiler. Correct also the the variable declarations of p1 and p2. Use this snip as an orientation:

#include <iostream>

class Person
{
private:
    int age;
    std::string name;
    int numOfKids;
public:
    Person()
    {
        this->age = 0;
        this->name = "bob";
        this->numOfKids = 5;
    }

    Person(int agee, std::string namee, int numof)
    {
        // ToDo
    }

    ~Person()
    {
        // ToDo
    }

    std::string toString()
    {
        // ToDo
        return "";
    }
};

int main()
{
    Person p2;
    Person p1;
    std::cout << p1.toString() << std::endl;
    return 0;
}

Upvotes: 0

Related Questions