-2

I've been programming in Java and C# for a while and I guess I always thought of objects and classes as being one and the same but the C++ course I'm following has the classes in .h files and the objects .cpp files. Is this typically how a C++ program is structured? Is the class/object relationship different than other OOP's?

sergej
  • 17,147
  • 6
  • 52
  • 89
BBDev
  • 93
  • 1
  • 1
  • 8
  • By taking the following declaration: `int a;`, class is to the object as `int` is to the `a`. – Algirdas Preidžius Aug 22 '16 at 11:57
  • 1
    Not really. C++ having declarations (interface) in one file and the implementation in another is just a convention. See [.c vs .cc vs .cpp vs .hpp vs .h vs .cxx](http://stackoverflow.com/questions/5171502/c-vs-cc-vs-cpp-vs-hpp-vs-h-vs-cxx) – Bo Persson Aug 22 '16 at 12:08
  • https://en.wikipedia.org/wiki/Object_(computer_science) https://en.wikipedia.org/wiki/Class_(computer_programming) – n. m. could be an AI Aug 22 '16 at 12:36

2 Answers2

1

The relationship between the class and the object is not different to other languages. The object is an instance of the class.

So for example:

Car myCar("licence-plate123");

Car is the class. myCar is an instance of the Class Car and therefore the object.

To seperate the Class declaration is more like a convention and has nothing to do with objects and classes.

The .h-File contains the class description. There you can see, which methods the class provides, and what parameters they need. The .cpp-Files describe how each method works. So the actual source-code.

But as I have already said: This is more like a convention. You can also write all of it in the .h-File. It's not pretty but it works

Andreas
  • 309
  • 1
  • 8
  • Ok so I guess what confused me is that a class's description, method's are all contained in a single .cs fie in c# but in c++ the object's properties and methods have to be described in the .h before implemented in the .cpp. Is this right? – BBDev Aug 22 '16 at 13:05
  • Yes that's right. Although, as mentioned, you do not have to – Andreas Aug 22 '16 at 13:08
  • Great! Thank you very much this really helped everyone. – BBDev Aug 22 '16 at 13:19
1

You might as well see classes declarations in a .cpp file, e.g., if the one who wrote this file decided to use some help-classes that weren't supposed to be part of the API presented in the .h file. Also, you might see in a .h file an object that is being held within a class as its private member.

Indeed, Java "pushes" you towards a pretty strict source and class files organization, that in many cases will match your folders & files organization. C++ allows you much more freedom in this regard, but however has the notion of includeing header files.

OfirD
  • 9,442
  • 5
  • 47
  • 90