Introduction to Classes |
|
In the previous lesson, we introduced data types that are usually referred to as primitive. Each of these data types is used to create an object that can hold a single value, such as the number of bedrooms of a house, the type of house, etc. Here are examples of such variables:
Notice that, in this example, some or all of the variables could be used to create a single object.
The C++ language allows you to use one, or a group of more than one, type of values to create what would be referred to as a composite type. This type is created as a class. As introduced in Lesson 1, to create a class, start with either the struct or the class keyword, followed by a name and ending with a semi-colon. The name of the class follows the same rules we have been applying to the variables so far. Here is an example: struct House; Or class House; We we will start the names of our classes with C: struct CHouse; Or class CHouse;
struct CHouse{ }; Or class CHouse{ }; In the body of the class, you can list the items that compose it. Each item is called a member of the class. Each item is identified by its type and a name. For example, if you want to create a CHouse class that is simply known for its value, you can define a member value of double type. Such a class would look like this: struct CHouse{ double Value; }; Or class CHouse{ double Value; }; Most objects are made of various parts. Listing all parts on a single line could be cumbersome. Therefore, you can span the body of a class on various lines. An example would be: struct CHouse { // Body of the class }; or struc CHouse { // Body of the class }; Or class CHouse { // Body of the class }; or class CHouse { // Body of the class }; In the body of the class, you can then list its members. Each member is created as a variable, declaring it using any of the techniques we used in the previous lesson. Here are examples:
If two variables are of the same type, you can declare them with one data type as done for variable declarations in the previous lesson. Here is an example:
To indicate that a member variable belongs to the class, another way you can declare it is by preceding its name with the name of the class followed by the :: operator. Here are example:
|
|
||
Previous | Copyright © 2006-2016, FunctionX, Inc. | Next |
|