Classes |
|
The variables we have used so far in a program are declared from a single data type. To create more advanced and complete objects, you can group data types and create a newly defined type. Object Oriented Programming, or OOP, is a technique of creating an object made of various, known, and existing types, leading to a more advanced and sophisticated object. The most fundamental of the C++ objects is called a structure. In Lesson 1, we saw that a class could be created as a structure, using the struct keyword, followed by a name for the class. We also mentioned that the members of a class were listed between an opening curly bracket "{" and a closing curly bracket "}", ending with a semi-colon. Based on this, we listed the following structure of a class: struct CHouse { Walls; Doors; Roof; TypeOfFloor; }; The Walls, Doors, Roof, and TypeOfFloor are referred to as members of the class. Each member of a class is created following strict rules. A member is declared like a normal variable. This means that it must have a data type and a name but should not (in fact must not, but we will learn an exception to this rule) be initialized. As a normal declaration, the variable must end with a semi-colon. A class can be another technique of redefining an existing data type, as we saw with the typedef keyword. Such a class would have only one member. Here is an example: // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h" #using <mscorlib.dll> using namespace System; struct CHouse { int PositiveNumber; }; int _tmain() { // TODO: Please replace the sample code below with your own. Console::WriteLine("\n"); return 0; } In the same way, you can declare as many variables as you judge necessary for the functionality of the class. Here is an example: struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; };
After creating a class, in order to use it, you can declare its variable just like you would any other variable. There are various techniques you can use to declare the variable. Using the C technique, you can precede the name of the structure with the struct keyword. Here is an example: Here is an example: // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h" #using <mscorlib.dll> using namespace std; using namespace System; struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; int _tmain() { // TODO: Please replace the sample code below with your own. struct CCar vehicle; Console::WriteLine(); return 0; } You can also omit the struct keyword in the declaration, as is commonly done. As done with the other variables, you can declare various variables on the same line: CCar vehicle, hatchback, truck;
Like any other variable, you can initialize an object declared from class when creating it or after creating it. To initialize the variable when creating it, on the right side of the variable's name, type = followed by an opening curly bracket and ending with a closing curly bracket. Between the brackets, provide a value for each member of the class separated by a comma. The list must be created in the exact order the members appear in the class. If a member is a char type, its value must be included in single-quotes. If a member is a string, its value must be included in double-quotes. Here is an example: // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h" #using <mscorlib.dll> using namespace std; using namespace System; struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; int _tmain() { // TODO: Please replace the sample code below with your own. struct CCar vehicle = { "Ford", "Escort", 5, true }; Console::WriteLine(); return 0; } Another technique to initialize the variable consists of accessing each member (in any order) and assigning it the desired but appropriate value. To access a member of the class, type the name of the variable, followed by a period, followed by the name of the member you want to access. This access allows you to do what you need on the member. For example, you can assign it a value or change the value it is holding. Microsoft Visual Studio can help you remember and select the right member of an object using a feature called Intellisense. When using a class' variable, type the name of the declared variable followed by a period. Visual C++ will display the list of accessible members. You can then choose one in the list. Type the first letter of the member and it would be selected. If there is more than one member that starts with the same letter, you can continue typing subsequent letters or you can scroll in the list. You can also click the desired member in the list. Once the item is highlighted, press the Spacebar and continue your work. Here is an example that initializes a class' variable by accessing each of its members: // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h" #using <mscorlib.dll> using namespace std; using namespace System; struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; int _tmain() { // TODO: Please replace the sample code below with your own. struct CCar vehicle = { "Ford", "Escort", 5, true }; CCar registered; registered.HasAirCondition = false; registered.Model = "Corolla"; registered.NumberOfDoors = 4; registered.Make = "Toyota"; Console::WriteLine(); return 0; } You can also use this same access technique to display the value of a member of the class. Using this syntax, you can display the value of a class member: Console::Write(vehicle.Make); Using the Console::Write() method to display the values of the object members. Here is an example: #using <mscorlib.dll> #include <string> #include <iostream> using namespace std; using namespace System; struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; int _tmain() { CCar vehicle = { "Ford", "Escort", 5, true }; CCar registered; registered.HasAirCondition = false; registered.Model = "Corolla"; registered.NumberOfDoors = 4; registered.Make = "Toyota"; cout << "Vehicle Inspection\n"; cout << "Make: " << vehicle.Make << "\n"; cout << "Model: " << vehicle.Model << "\n"; cout << "Doors: "; Console::WriteLine(vehicle.NumberOfDoors); cout << "Has A/C: "; Console::WriteLine(vehicle.HasAirCondition); Console::WriteLine(); return 0; } This would produce: Vehicle Inspection Make: Ford Model: Escort Doors: 5 Has A/C: True Press any key to continue
We have just seen that, like any other variable, before using a class, you must first declare it. Although the usual technique consists of declaring the variable when and where needed, C++ supports another technique. You can declare the variable when creating it. To do this, type the name of the class between the closing curly bracket and the semi-colon. Here is an example:
In this case, the hatchback variable is a valid instance of the class and gives access to the members of the class. This means that you can simply initialize any of its members as you see fit. Here is an example: #using <mscorlib.dll> #include <string> #include <iostream> using namespace std; using namespace System; struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; } hatchback; int _tmain() { hatchback.HasAirCondition = false; hatchback.Model = "Corolla"; hatchback.NumberOfDoors = 4; hatchback.Make = "Toyota"; cout << "Vehicle Inspection\n"; cout << "Make: " << hatchback.Make << "\n"; cout << "Model: " << hatchback.Model << "\n"; cout << "Doors: "; Console::WriteLine(HatchBack.NumberOfDoors); cout << "Has A/C: "; Console::WriteLine(HatchBack.HasAirCondition); Console::WriteLine(); return 0; } This would produce: Vehicle Inspection Make: Neon Model: Dodge Doors: 4 Has A/C: True Press any key to continue Just like you would declare more than one variable, you can declare many instances of an object when creating the object. Here is an example:
You can also use the typedef keyword to define a type structure and set the actual name of the structure between the closing curly bracket and the semi-colon. To do this, you must type a pseudo-name for the structure on the first line. Here is an example:
In this case, _Car is the name of the object and CCar is an alias for the name of the object. In other words, _Car and CCar mean exactly the same thing. The CCar name is a class, not a variable. Therefore, when you want to use the object, you must declare an instance of the class using either the _Name or the Name. Here is an example: #using <mscorlib.dll> #include <string> #include <iostream> using namespace std; using namespace System; typedef struct _Car { string Make; string Model; int NumberOfDoors; bool HasAirCondition; } CCar; int main() { CCar hatchback, SUV; _Car Truck; hatchback.Model = "Dodge"; hatchback.Make = "Neon"; hatchback.NumberOfDoors = 4; hatchback.HasAirCondition = true; cout << "Vehicle Inspection\n"; cout << "Make: " << hatchback.Make << "\n"; cout << "Model: " << hatchback.Model << "\n"; cout << "Doors: "; Console::WriteLine(hatchback.NumberOfDoors); cout << "Has A/C: "; Console::WriteLine(hatchback.HasAirCondition); Console::WriteLine(); return 0; } In some cases, the name of the structure in the first line may have a name that starts with tag: typedef struct tagPoint { int x; int y; } CartesianPoint;
Besides struct, C++ also provides the class keyword used to create a class. From all of the classes we have used to far, to create a class, you can replace the struct keyword with class. Here is an example: class CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; Of course, the first question that comes in mind is that, what's the difference if both are the same?... A common object in real life is visibly made of two categories of parts: those you can see or touch and those you don't have access to. The parts you can see or touch are considered visible or accessible. In C++, such parts are referred to as public. Those you cannot see or touch are considered hidden. In C++, such parts are referred to as private. Like objects in real life, a class is made of parts that the outside world cannot “see” and those the other objects can access. The other objects of the program are sometimes referred to as the clients of the object. The parts that the client of an object can touch in a class are considered public and the others are private (there are some others called protected that we will review eventually). In C++, the fundamental difference between a class and a structure is the default type of access applied to their members. By default, the members of a structure are public. By default, the members of a class are private. This means that, most of the time (if not all the time), you must explicitly create a public section on a class; most of the time, you can create a structure without specifying the access level. That's the way we have used structures so far. Since its members are public by default, we were not concerned with their level of access. When creating a class, you will define which items are public and which ones are private. The items that are public are created in a section that starts with the public keyword. The others are in the private section. The access keyword must end with a colon, as in public: or private:. If you do not specify these sections, all of the members of a class will be treated as private. Therefore, the following two classes are the same: |
#using <mscorlib.dll> #include <string> #include <iostream> using namespace std; using namespace System; struct CCar { string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; int main() { CCar vehicle = { "Honda", "Civic", 4, true }; cout << "Vehicle Inspection\n"; cout << "Make: " << vehicle.Make << "\n"; cout << "Model: " << vehicle.Model << "\n"; cout << "Doors: "; Console::WriteLine(vehicle.NumberOfDoors); cout << "Has A/C: "; Console::WriteLine(vehicle.HasAirCondition); Console::WriteLine(); return 0; } |
#using <mscorlib.dll> #include <string> #include <iostream> using namespace std; using namespace System; class CCar { public: string Make; string Model; int NumberOfDoors; bool HasAirCondition; }; int main() { CCar vehicle = { "Honda", "Civic", 4, true }; cout << "Vehicle Inspection\n"; cout << "Make: " << vehicle.Make << "\n"; cout << "Model: " << vehicle.Model << "\n"; cout << "Doors: "; Console::WriteLine(vehicle.NumberOfDoors); cout << "Has A/C: "; Console::WriteLine(vehicle.HasAirCondition); Console::WriteLine(); return 0; } |
The public and private keywords are referenced by their access level because they control how much access a variable allows. You can create as many public sections or as many private sections as you want. For example, the above class could be created as:
You can type the access level to the left of each member of the class:
As stated already, the members of a structure are public by default, meaning if you do not define the levels of access in a structure, all of its members are accessible outside of the object. If you need to, you can explicitly define which members of a structure can be public and which ones would be private by creating the desired levels of access. The effect would be the same:
When creating a class with different public and private sections, all of the declared member variables under an access level keyword abide by the rules of that access level. The fact that you use different public sections does not give different kinds of public levels to the member. A member variable declared as public in one public section has the same public level of access as any other member variable that is declared in another public section. There is no rule as to which section should come first. Simply remember that, for a class, if the top members are not given a level of access, then they are private. A variable that is declared in a class is referred to as a member of that class.
Because a program can be made of various building blocks (variables, functions, classes, etc), to manage it, C++ allows you to separate the program in different files. The file that holds a class' foundation is called a header file and has the extension .h To create a header file, on the main menu of Visual Studio .Net, you can click Project -> Add New Item... From the Add New Items dialog box, select the Header File icon, provide a name and click OK. In the header file, you can declare variables, create one or more classes, and do any other necessary thing (such as declaring some functions). Here is an example of the content of a header file: There is no strict rule as to what can go in a header file and what you can do with it. Although we mentioned that you can use a header file to create a class, you can also declare any necessary variable in it. Here is an example: #pragma once struct CSquare { double Side; double Perimeter; double Area; }; int number; To make sure that the header file has not been created anywhere in the program, you can ask the compiler to check it. This is done using the #ifndef preprocessor followed by a one-word name for the file. Once the compiler has made sure that the header file is unique, you can ask the compiler to define it. This is done using #define followed by the same name as #ifndef. At the end, signal the closing of the file with the #endif preprocessor. Here is an example:
Instead of #ifndef, you can use the #if !defined followed by an identifier and you would receive the same effect: #if !defined SquareH #define SquareH struct CSquare { double Side; double Perimeter; double Area; }; int number; #endif SquareH Instead of using a combination of the #ifndef and #endif or a combination of #if !defined and #endif, you can use a #pragma once in the top section of the file. The above file could be created as: #pragma once struct CSquare { double Side; double Perimeter; double Area; }; int number; There are two main types of header files you will be using in your programs: those you create and those that have been supplied to you. To include a header or source file that you created, type #include followed by the name of the file in double-quotes as follows: #include "File2.h" To use a header file that was installed with the compiler, include its name between the < and the > operators. Here is an example: #include <string>
By tradition, a header file is used to lay a foundation for classes or other variables that other sections of a program may need. Also, by tradition, a header file is usually accompanied by another file, called a source file. A source file is used to use or define the class(s) and other variables that were created or initiated in a header file. In modern programming, you can use these files interchangeably. A source file has the extension .cpp. When you create a Console Application using Visual C++ .NET, a source file with the name of the project is automatically created for you. You can then add as many other source files as you judge necessary. As mentioned above, while in one file, if you want to use the contents of another file, whether the other is a header file or a source file, you must first include it: #include "File1.cpp" After creating a class in a header file, you can use such a class in another file such as the source file created automatically when using the Console Application; simply include its header file. Here is an example: // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h" #include "Square.h" #using <mscorlib.dll> using namespace System; int _tmain() { // TODO: Please replace the sample code below with your own. CSquare plate; number = 15; plate.Side = 35.55; plate.Perimeter = plate.Side * 4; plate.Area = plate.Side * plate.Side; Console::WriteLine("Square Characteristics"); Console::WriteLine("Side: {0}", __box(plate.Side)); Console::WriteLine("Area: {0}", __box(plate.Area)); Console::WriteLine("Perimeter {0}", __box(plate.Perimeter)); Console::WriteLine("\nNumber: {0}", __box(number)); Console::WriteLine(); return 0; } This would produce: Square Characteristics Side: 35.55 Area: 1263.8025 Perimeter 142.2 Number: 15 Press any key to continue
Variables, functions, and classes can be part of a namespace. To create a class in a namespace, first type the namespace keyword, followed by a name for the namespace, followed by the opening bracket that starts a namespace. In the body of the namespace, start creating the class the same way you would proceed for any regular class. At the end of the class, remember to end the namespace with its closing curly bracket. Here is an example:
As mentioned for the header file, there is no strict rule as to what goes in a namespace, as long as it is appropriately set. This means that, besides classes, you can declare variables in a namespace. Here is an example: #pragma once namespace FlatShapes { struct CSquare { double Side; double Perimeter; double Area; }; int number; }
This is just a reminder of what we reviewed in Lesson 1 about namespaces. To reference a class or anything that is part of a namespace, from outside of the namespace, you can type the name of the namespace, followed by the :: operator, followed by the class or item you want to access. Here are examples of how to access the class and variable that are part of the above FlatShapes namespace from the main source file of the program:
An alternative to accessing members of a namespace from another section of the program, as we saw in Lesson 1, consists of using the using namespace expression. To do this, type using namespace followed by the name of the namespace, followed by a semi-colon. After this statement, you can access the members of the namespace using only their names. Here is an example: // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h" #include "Square.h" #using <mscorlib.dll> using namespace System; using namespace FlatShapes; int _tmain() { // TODO: Please replace the sample code below with your own. struct CSquare plate; number = 15; plate.Side = 35.55; plate.Perimeter = plate.Side * 4; plate.Area = plate.Side * plate.Side; Console::WriteLine("Square Characteristics"); Console::WriteLine("Side: {0}", __box(plate.Side)); Console::WriteLine("Area: {0}", __box(plate.Area)); Console::WriteLine("Perimeter {0}", __box(plate.Perimeter)); Console::WriteLine("\nNumber: {0}", __box(number)); Console::WriteLine(); return 0; } Even if you include the using namespace statement, in some cases, to make sure you are accessing the actual member of a namespace, you can still type the name of the namespace followed by the desired member. This is referred to as qualifying a name (when using the name of a namespace followed by the :: operator and the name of the member, it is said that you are qualifying the member of the namespace). There is absolutely no inconvenience to that. In fact, it is always advantage to qualify a member of a namespace when using it: this eliminates, otherwise highly reduces, the possibility of a name conflict.
|
|
||
Previous | Copyright © 2004-2010 FunctionX, Inc. | Next |
|