user3083522
user3083522

Reputation: 211

c++ class in one file

I am new to C++. For the moment I don't want to use separate compilation. But when I create a class in Eclipse it automatically creates the class.h and class.cpp. Which file can I use to write the whole class in without separate compilation?

Upvotes: 0

Views: 3281

Answers (3)

chase993
chase993

Reputation: 16

Here is a small example I made:

#include <iostream>

using namespace std;

class Person
{
public:

    Person()
    {

    }

   ~Person()
    {

    }

    string getName()
    {
        return name;
    }

    void setName(string newName)
    {
        name  = newName;
    }

    int getAge()
    {
        return age;
    }

    void setAge(int newAge)
    {
        age = newAge;
    }

    void toString()
    {
        cout << "Hello my name is " << name << ", and I'm " << age << " years old." << endl;
    }
private:
    string name;
    int age;
};

int main()
{
    Person p;
    p.setAge(20);
    p.setName("Bob");
    p.toString();
    return 0;
}

OUTPUT

Hello my name is Bob, and I'm 20 years old.

Upvotes: 0

4pie0
4pie0

Reputation: 29734

Dividing files into .h and .cpp doesn't introduce separate compilation. All headers are included by source files.

When you #include a file, its contents are copied verbatim at the place of inclusion.

Thus, you should never include a .cpp file. If you want to compile a file, pass it to the compiler. If you both #include and compile a source file, you'll get multiple definition errors.

Upvotes: 2

MooseBoys
MooseBoys

Reputation: 6793

You should be able to declare and implement the class entirely in the .cpp file and simply delete the .h file. You won't be able to use the class in other .cpp files, however, without a bunch of extern declarations. For example:

// foo.cpp
#include <iostream>
class Foo
{
    Foo() { std::cout << "Hello!" << std::endl; }
    ~Foo() { std::cout << "Goodbye!" << std::endl; }
};

Upvotes: 0

Related Questions