|
To | Do this |
Define a class. | Add a header file to your project. Define the class in the header file. For example: class MyClass { public: void MyFunction(); private: int myData; }; |
Implement a class. | Add a source file to your project. In the source file, use a #include statement to include the header file that contains the class definition. Then implement the member functions in the source file. For example: #include "MyHeader.h" void MyClass::MyFunction() { myData = myData * 2; } |
Provide a constructor in a class. | Declare the constructor in the header file, and implement it in the source file. The constructor must have the same name as the class and cannot return a value. However, a constructor can take parameters. For example: // Header file class MyClass { public: MyClass(int n); ... }; // Source file MyClass::MyClass(int n) { myData = n; } |
Provide a destructor in a class. | Declare the destructor in the header file, and implement it in the source file. The destructor must have the same name as the class, preceded by a tilde (~). The destructor cannot return a value or take any parameters. For example: // Header file class MyClass { public: ~MyClass(); ... }; // Source file MyClass::~MyClass() { Console::WriteLine(S"Goodbye"); } |
Create and destroy objects of an unmanaged class. | Create an object using the new keyword, passing parameters into the constructor if necessary. Delete the object using the delete keyword. For example: MyClass * ptrToObject; ptrToObject = new myClass(100); ptrToObject->MyFunction(); delete ptrToObject; |
Define class-wide data members. | Declare the data member using the static keyword. Define the data member in the source file. For example: // Header file class MyClass { private: static int myClassData; ... }; // Source file int MyClass:myClassData = 0; |
Define and use class-wide member functions. | Declare the member function using the static keyword. Implement the member function in the source file. Call the function using the syntax ClassName::FunctionName. For example: // Header file class MyClass { public: static void MyClassFunction(); ... }; // Source file void MyClass::MyClassFunction() { myClassData++; } // Client code MyClass::MyClassFunction(); |
Define relationships between objects. | Define all the required classes, and use pointers to denote relationships between objects. For example, if an instance of class A needs to point to an instance of class B, use the following: class B { ... }; class A { ... private: B * pointerToB; }; |
|