C++ Review: Classes


Classes in C++

A C++ class contains data members and member functions (called methods). Data members and methods can be either A class constructor: A class can also have a destructor:

Example: Class declaration

Here is the declaration of the class Point:

class Point
{
public:
	Point();
	Point(int xval, int yval);
	void Move(int dx, int dy);
	int Get_X() const;
	int Get_Y() const;
private:
	int X;
	int Y;
};
Method implementation can be found here.


Objects

An object is an instance of a class.
A particular object has: To create an object, we (implicitly) use the constructor:

Point p1;
Point p2(2, 3);

Which one uses the default constructor?

We can also call a member function for a particular instance of a class:

p1.Move(1, -1);          // change p1’s coordinates
cout << p2.Get_X();      // output p2’s X coordinate     
Can we use “cout << p2.X” ? Why?

Exercises

Some basic exercises can be found here. We will not cover this in the our lab, as this is cs111 material you should be able to solve. However, if you find you have a problem solving any of these, please let us know!



Original page created by Jisook Youn and Jing Zhong for cs111.
Modified by Gali Diamant gali@cs.bu.edu
Material partially taken from the textbook "Computing Concepts with C++ Essentials", by Horstmann.

Last modified Jan 22, 2003