Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class defined in separate file

Tags:

c++

Is it possible to create an object in file A.cpp if its class is defined in file B.cpp?

What I mean is, you can use extern to access a variable initialized in another file. Is there anything similar for classes?

like image 543
john smith Avatar asked Jun 28 '11 11:06

john smith


1 Answers

No. The class definition must be visible to the compiler in the current translation unit if you actually instantiate/use that class.

Usually you have the definition of the class in a header file that will be included in every .cpp that needs to use that class. Notice that usually methods inside a class definition are only declared, since their implementation (definition) is usually put in a separate .cpp file (unless you have inline methods, that are defined inside the class definition).

Notice however that you can get away with just a class declaration (usually called forward declaration) if all you need is to declare/define pointers to the class - i.e. if all the compiler needs to know is that a type with that name will be defined later before you actually need to do something on it (instantiate the class, call its methods, ...). Again, this is not enough to define a variable/member of the type of the class, because the compiler has to know at the very least the size of the class to decide the memory layout of the other class/of the stack.

To recap about the terminology and about what you can/cannot do:

// Class declaration ("forward declaration")
class MyClass;

// I can do this:
class AnotherClass
{
public:
    // All the compiler needs to know here is that there's some type named MyClass
    MyClass * ptr; 
};
// (which, by the way, lets us use the PIMPL idiom)

// I *cannot* do this:

class YetAnotherClass
{
public:
    // Compilation error
    // The compiler knows nothing about MyClass, while it would need to know its
    // size and if it has a default constructor
    MyClass instance;    
};

// Class definition (this can cohexist with the previous declaration)
class MyClass
{
private:
    int aMember;    // data member definition
public:
    void AMethod(); // method declaration

    void AnInlineMethod() // implicitly inline method definition
    {
        aMember=10;
    }
};

// now you can do whatever you want with MyClass, since it's well-defined
like image 190
Matteo Italia Avatar answered Oct 16 '22 09:10

Matteo Italia