Objects in C++

Is anyone able to concisely explain and help me better understand Objects in C++. From my understanding, they act as a ‘template’ to apply certain data and functionality to an object in the game/code. The .h(header file) is used to establish this data and functionality, and the .cpp file is used to implement it. However, the part I’m having trouble wrapping my head around is, coming from Unity and C#, I am used to there being a ‘main script’ which codes for something. I’m not used to there being two different scripts for one thing like a character, or at least that’s how I understand it. Anyway, if anyone can help correct my understanding and explain it better I will be very grateful. Thanks.

To be clear on terms, objects in the C++ sense (not OOP sense) are just a region of memory that have some value of some type. What you appear to be describing are classes which are a way to define your own type (known as user-defined types).

Your question is really about the compilation model of C++ and not really about classes. In C++ everything needs to be declared before you can use it. e.g.

//main.cpp

int main()
{
    int value = square(3);
}

int square(int n) 
{ 
    return n * n; 
}

Attempting to compile this file would result in an error as the compiler would get to the first line of main and complain it has no idea what square is; even though it’s defined right below. I can add

int square(int);

above main to fix this. Now the compiler knows that square is a function that takes an int and returns an int, everything it needs to know in order to know what to do when it sees its use in main.

Now lets say I have multiple files all wanting to use square, I could manually declare it at the top of all the files that use it but that would be tedious and error prone. Instead I could leverage the preproccesor to copy and paste that for me (#include). By creating a header file with the contents

// only include this once per compilation of a file
#pragma once

int square(int n);

And now I just include this header to get its declaration. Its also important to note that it only needs to be defined once and the linker will link its use with the definition. Having the definition within the header file would mean all files that include it would be compiling their own copy of the definition and would run afoul of One Definition Rule violations.

See also:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms