C++ Design Pattern
Week One (Overview of Course): Step Assignments: About 6 Design Assignments: About 10
To Do: Read Chapter One in Object-Oriented Modeling Do Step 1 of the Assignment
Week Two: • Review basic OOP Concepts • Review Inheritance and Polymorphism • Work on “Square” program • Objects vs Classes • Constant Functions and Constructors • Pointers
Work on “Square” program
Let’s say we want to describe a square
Heres the header file
#ifndef CSQUARE_H_
#define CSQUARE_H_
class CSquare{
private:
int mX; // Center x
int mY; // Center y
int mWidth; // Width of the square
public:
CSquare() : mX(0), mY(0), mWidth(100){}
int GetX() const {
return mX;
}
void SetX(int x)
{
mX = x;
}
int GetY() const {
return mY;
}
void SetY(int y)
{
mY = y;
}
int GetWidth() const {
return mWidth;
}
void SetWidth(int w)
{
mWidth = w;
}
}
#endif /* CSQUARE_H_ */
What do these do?
- These are the #include Guard
#ifndef CSQUARE_H_
#define CSQUARE_H_
// code
#endif /* CSQUARE_H_ */
Objects vs Classes
Now what is the difference between the two?
-
Class: A type, which defines what an object will contain
-
Object: An instance of the class
Constant Functions and Constructors
-
const funciton is not allowed to change the object and is guaranteed not to.
-
{} is the code to run to construct an object of our class CSquare
Inheritance
- Inheritance creates new classes based on the classes that have already been defined. The capabilities of the base class are inherited by the dervied class
Advantages of Inheritance
- Factors out code that is common in multiple classes
- Dervied class inherits noth function and data members from the base class
- Dervied class can add additional functions or data memebers
- Dervied class can override inherited function memebers with new methods
Example
class CShape{
private:
int mX; // Center x
int mY; // Center y
public:
CShape() : mX(0), mY(0),){}
int GetX() const {
return mX;
}
void SetX(int x)
{
mX = x;
}
int GetY() const {
return mY;
}
void SetY(int y)
{
mY = y;
}
}
// Two Derived Classes
// Square Class
class CSquare :public CShape
{
private:
int mWidth; // Width of the square
public:
CSquare(): mWidth(100){}
int GetWidth() const
{
return mWidth;
}
void SetWidth(int w)
{
mWidth = w;
}
}
// Oval Class
class COval :public CShape
{
private:
int mWidth;
int mHeight;
public:
COval :mWidth(100), mHeight(100) {} // constructor
int GetWidth() const
{
return mWidth;
}
int GetHeight() const
{
return mHeight;
}
void SetSize(int w, intg h)
{
mWidth = w;
mHeight = h;
}
}
Pointers
Week Three
Polymorphism in C++
Virtual Functions