Learn C++ in step-by-step lessons.
Classes: Creating a simple Rectangle class
In this lesson we will go through several steps to create a rectangle class. These steps will give you an overview of some of the features and advantages of using a class.
Bear in mind that a rectangle is fairly simple, other classes may have a great more complexity.
Note: All code shown works for the latest version of Microsoft Visual Studio. If you are not using tat, please get a simple "Hello World" program working and adjust as necessary.
Goals:
- Understand and modify a simple Rectangle class
Objectives:
- Know basic object oriented terminology
- Explain why member variables are madee private
- Explain getter and setter methods
- Be able to use friend ostream
- Give examples of overloaded operators
- Move Rectangle class to separate files
- Use a class in a program
Please study the material at each of the links below.
- Class terminology: Basic object oriented terminology
- Class Guidelines: Basic guidelines and principles
Rectangle class 1: private width and length: Step 1 creates the private member varaibles length and width, constructors, and the getter and setter methods.
Rectangle class 2: user input, check for errors: Step 2 adds user input and checks for errors in main, not the class
Rectangle class 3: friend ostream: Step 3 adds ostream as friend so cout<
Rectangle class 4: methods area and diagonal: Step 4 adds methods area and diagonal.
Rectangle class 5: overload operators for comparing: Step 5 adds comparison operators
Rectangle class 6: overload operators = and +: Step 6 adds assignment = and addition + operators- Rectangle class 7: Other additions: Step 7 challenges you to add additional methods to the class.
Rectangle class in separate files: Create the Rectangle as Rectangle.h and Rectangle.cpp
Include the Rectangle class : Include Rectangle.h and Rectangle.cpp
Glossary for rectangle lesson
Full Glossary