Search code examples
c++declarationdeclare

how can i declare a Class in C++


I want do declare the class Person before the main method but it gives me an error that the class Person is undefined

The main method is making the Object Person but I don't know how I can declare it like I do with methods.

//main Function
int main()
{
    Person person = Person("Majd", 18, 177); //Error "Person class is undefined"
    person.printPerson();
}

class Person
{
    //Private Attributes
    int age;
    int height;
    string name;
    //Public Atributes
public:

    Person(string name, int age, int height) {
        setName(name);
        setAge(age);
        setHeight(height);
    }
    //Getters
    string getName() {
        return name;
    }
    int getAge() {
        return age;
    }
    int getHeight() {
        return height;
    }
    //Setters
    void setName(string name) {
        this->name = name;
    }
    void setAge(int age) {
        this->age = age;
    }
    void setHeight(int height) {
        this->height = height;
    }

    void printPerson() {
        cout << "Name: " << getName() << " Age: " << getAge() << " height: " << getHeight();
    }
};

I am doing it like that so I can learn how to declare classes.


Solution

  • If you delcare the class above main:

    class Person;

    then you will be able to do

    Person * person = 0; or Person * person = some_other_person;

    but without being told that there are constructors to link against it will not be possible to actually create a person here, or use one.

    You could just move the entire class definition to the top of the file, above main. That will fix it for now.

    Good programming style would be to make a file called Person.h, put your class in that, and then #include "Person.h" in your main cpp file.