Lecture02 OOP Review
Lecture02 OOP Review
Lecture02 OOP Review
Review
1
Object-Oriented Programming
Object-Oriented Programming languages vary but
generally all support the following features:
Data Abstraction (encapsulation) – Define types
with an interface and hidden implementation.
class Point {
public:
Point(int a, int b=0): x(a), y(b) {}
void draw() const;
private:
int x, y;
};
3
C++ Revision
Constructors are used to create and initialise a
new object. Every constructor should initalise
every data member.
4
C++ Revision
If you don’t write any constructors, the compile
will supply a default constructor.
Point(): x(), y() {}
5
C++ Revision
C++ classes can be referred to in three different
ways. Each have implications when assigning
variables to each other:
6
C++ Revision
Methods which are defined in the class are
inline. Functions longer than a few lines should
not be defined here.
7
C++ Revision
Methods have access to private members of other
objects of the same class.
8
C++ Static
Static data members are shared by all objects of a
class. It is initialised in a declaration outside the
class.
class Counter {
public:
Counter() {++count;}
~Counter() {--count;}
Counter(const Counter& c) {++count;}
Counter& operator=(const Counter& c) {return *this;}
static int getCount() {return count;}
private:
static int count;
};
int Counter::count = 0;
9
C++ Operators
Operators may be overloaded for classes as either
a global function with one parameter for each
operand or as a method of the left-hand operand.
10
C++ Inheritance
Inheritance allows a derived class to inherit all
the members of a base class except the
constructors, destructor and assignment
operator.
11
C++ Inheritance
Important terms you should know:
12
C++ Polymorphism
Polymorphism class hierarchies consist of an
interface (abstract base class) and a set of derived
implementations.
13
C++ Overriding Methods
A method overriding a base method must have
the same parameters, return type and const-ness.
14
C++ Programming
Generally you should not create objects of an
abstract class or interface.
15
Example
class Complex{
public:
Complex(double real, double imaginary=0):
_real(real),_imaginary(imaginary){}
void operator+(Complex other){
_real = _real + other._real;
_imaginary = _imaginary + other._imaginary;
}
void operator <<(ostream os){
os <<"("<<_real<<","<<_imaginary<<")";
}
Complex operator++(){
++_real;
return *this;
}
Complex operator++(int){
Complex temp = *this;
++_real;
return temp;
}
private:
double _real,_imaginary;
};
16
Example
class Complex{
public:
explicit Complex(double real, double imaginary=0):
mReal(real),mImaginary(imaginary){}
Complex& operator+=(const Complex& other){
mReal += other.mReal;
mImaginary += other.mImaginary;
return *this;
}
Complex& operator++(){
++mReal;
return *this;
}
const Complex operator++(int){
Complex temp(*this);
++*this;
return temp;
}
private:
double mReal, mImaginary;
};
17