Class defined in a separate file

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

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

+4
source share
2 answers

No. The class definition should be visible to the compiler in the current translation unit if you are actually instantiating / using this class.

Usually you have a class definition in the header file that will be included in every .cpp that this class should use. Note that usually methods inside a class definition are declared only after their implementation (definition) is usually placed in a separate .cpp file (unless you have inline methods that are defined inside the class definition).

Please note that you can get just a class declaration (usually called a forward declaration) if you only need to declare / define pointers to the class, that is, if all compilers need to know, this type with that name will be defined later, before you really you need to do something (create an instance of the class, call its methods, ...). Again, this is not enough to define a variable / member of a class type, because the compiler must know at least the size of the class in order to determine the memory layout of another class / stack.

To learn about terminology and 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 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 well-defined 
+5
source

If you mean:

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

Then no, how do you need a class definition (at least know its size).

However, you can use the factory method to achieve the same result while you argue with an opaque pointer to an object (for example, if class B inherits from some interface).

+2
source

All Articles