> Having trouble understanding classes in C++?

Having trouble understanding classes in C++?

Posted at: 2014-12-18 
Sure I'll take a stab at it.

I will assume you have basic C++ understanding, like arrays, int, string and so on. I will also assume this is your first language.

The best example I like to use for a Class is that if you are printing money you need something to hold the image of the money. This is your class. Then the actual money that was printed is a object. As such the class holds all the information about an object, but it is not the object itself, it is a template of the object. A class can contain anything else, including classes. As such it can have sub-classes, strings, arrays, functions, and so on. Another feature is that you can make the content of the class Private or Public. If it is Public then any other part of the program can see it, if it is private only the Class itself can see it.

To write a class you treat it similar to a function:

class Money

{

public:

double amount;

double size;

string color;

};

However this would only be a template of the object, as such you will have to initialize a class in any program. The same way you give a int a value you must then give the class a value. To access a part of a class you first write the variable name dot the name of the variable inside of the class.

...

int main()

{

...

Money Dollar;

...

Dollar.amount = 1;

Dollar.size = 1

Dollar.color = "green"

...

}

Once you write Money Dollar; the compiler will assign a space in memory to store the class. However since it is not initialized the memory will contain random information. As such you must assign a value to it. The simplest way to do this is to create a function inside of the class that does this for you. However it is not required.

In the above example, Money is the class, Dollar is the Object. Unless it is a static variable inside of a class, you must use the Object name (Dollar) to access the variables inside of a class. The same way you don't do int = 5 you do not do Money = 5. Money is a Class, which is a template, not a Object.

I hope the above helps. It can take a while to understand classes, but once you do you will wonder how you could not have understood it before...

Hello, I am having an extremely hard time understanding classes in C++, can someone please explain classes and the basics on writing and using classes in the most simple form? Or supplying a webpage that will help me understand classes better?