john smith
john smith

Reputation: 649

Class defined in separate file

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?

Upvotes: 5

Views: 2593

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126787

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

Upvotes: 6

user786653
user786653

Reputation: 30460

If you mean like:

// B.cpp 
class B { /* ... */ };

// A.cpp
B* b = new B();

Then no as you need the class definition (to know its size at least).

However you can use a factory method to achieve the same outcome as long as you are contend with an opaque object pointer (for example if the B class inherits from some interface).

Upvotes: 3

Related Questions