Why is there no multiple definition error when you define a class in a header file?

前端 未结 3 1926
粉色の甜心
粉色の甜心 2020-12-09 11:40

I\'m not sure if I asked the question correctly, but let me explain.

First, I read this article that explains the difference between declarations and definitions: htt

3条回答
  •  自闭症患者
    2020-12-09 11:52

    Your class definition defines the class, but does not define and objects of that class. It's OK to have the class (or structure) defined in multiple files, because you're just defining a type, not a variable of that type. If you just had the definition, no code would be emitted by the compiler.
    The compiler actually emits code only after you declare an object (i.e. variable) of this type:

    class MyClass myvar;
    

    or:

    class MyOtherClass { 
        public: ...
        private: ...
    } myvar;         // note the variable name, it instantiates a MyOtherClass
    

    That is what you do NOT want to do in headers because it will cause multiple instances of myvar to be instantiated.

提交回复
热议问题