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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
.cppthat 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.cppfile (unless you haveinlinemethods, 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: