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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With