0% found this document useful (0 votes)
23 views

OOP - Topic 07 - Lecture - Introduction To C++

This document provides an introduction to C++ and key concepts of object-oriented programming including encapsulation, inheritance, and polymorphism. It discusses how C++ supports these OOP principles through syntax like classes, public/private access modifiers, and virtual functions. Real-world examples are given to illustrate core C++ features and their applications in areas like systems programming, performance computing, and embedded systems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

OOP - Topic 07 - Lecture - Introduction To C++

This document provides an introduction to C++ and key concepts of object-oriented programming including encapsulation, inheritance, and polymorphism. It discusses how C++ supports these OOP principles through syntax like classes, public/private access modifiers, and virtual functions. Real-world examples are given to illustrate core C++ features and their applications in areas like systems programming, performance computing, and embedded systems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Introduction to C++

by Willem van Straten and Andrew Cain

Object Oriented Programming


Object oriented programming involves
creating objects that know and do things

Data Know things


&
&
Functionality
Do things
Syntax is secondary to good design
through application of OO Principles
When you understand the principles, you can understand
any OO language
See that syntax is similar
by learning a second language
Learning a second (human) language teaches you to
appreciate the grammar of your native tongue.
Why C++?
Available on every platform
Windows Linux

Mac Android

iOS etc….
High Performance Computing
(including games)
Digital Signal Large Scale
Processing Simulations

Graphics Real-time
Processing systems
Energy Efficient Computing
(including mobile apps)

• C++ programming languages are more energy efficient than others because they simply run
faster
• A program that can be executed faster reduces the load on a CPU, which in turn demands less
energy from the massive data centers that pull electricity from the grid.
Embedded Systems
(including device drivers)
Embedded PCs
Microcontroller

Toasters
RTOSes
Flexibility
C++ is a multi-paradigm
language:

•Object-oriented
programming

•Procedural programming

•Generic programming
Legacy C++ can utilize code written in C
and Fortran. They have
powerful C++ libraries: e.g.
Standard Template Library
(STL), QT GUI library, Eigen
Matrix Library for linear algebra
With great power comes great
responsibility

- François-Marie Arouet
Resource Management

e.g. any object created with new


must also be destroyed with delete
There is no Garbage Collector
Flexibility = Decision = Debate

(too) many ways to achieve


the same objective
Different design teams may choose different paradigms, styles,
conventions, policies, etc.
Let’s have a look at
the principles of OOP
expressed in C++
Encapsulation 1.

complete separation between interface


and implementation
class Student all classes are public
{
string name;
string id;
Declaration of interface in
public: header file (e.g. Student.h)
string getDescription ();
};

#include interface
#include “Student.h”
string Student::getDescription ()
{ Definition/implementation in
return name + “ “ + id; source file (e.g. Student.cpp)
}
Encapsulation 2.

public, protected, and private


keywords control access to members
class Student
{
private: Everything declared after
std::string name; private: is private.
std::string id;
public:
string getDescription ();
void getName (); Everything declared after
}; public: is public.
Encapsulation
Recap on Definition:
“Encapsulation is the process of combining data and function into a
single unit called class.”

“Encapsulation is the mechanism that binds code and data together and
keeps them safe and away from outside inference and misuse.”
Box.h (Header file) Box.cpp (Implementation)
#include<iostream> #include “Box.h”
using namespace std; // constructor (implementation)
class Box{ Box::Box(int l, int b, int h){
private: length = l;
int length; breadth = b;
int breadth; height = h;
int height; }
public: //setter (implementation)
//constructor void Box::setLength(int l){
Box(int l, int b, int h); length = l;
//setter }
//getter (implementation)
void setLength(int l);
int Box::getLength(){
//getter
return length;
int getLength();
}
//calculate volume
//calculate volume (implementation)
int volume();
int Box::volume(){
return (length*breadth*height);
};
}
Main.cpp
#include<iostream>
using namespace std;
int main(){
//creating a Box object
Box *b1 = new Box(2,3,4);
//calculating and display the volume of Box b1
cout<<“\nThe volume of Box b1 is “ << b1->volume();
//change the length of Box b1
b1->setLength(10);
//calculating and display the volume of Box b1
cout<<“\nThe new volume of Box b1 is “ << b1->volume();
return 0;
}
Inheritance
class Rectangle : public Shape
{
public:
void draw ();
}; implicit override

Note that inheritance is always public.

Protected and private use of a base class do not represent


an inheritance relationship
class Parent{ class ChildY : protected Parent{
public: // a is protected
int a; // b is protected
protected: // c is not accessible from
int b; ChildY
private: };
int c;
}; class ChildZ : private Parent{
// a is private
class ChildX : public Parent{ // b is private
// a is public // c is not accessible from
// b is protected ChildZ
// c is not accessible from };
ChildX
};
Inheritance
Recap on definition:
“Inheritance is a technique used in OOP that one object acquires the
properties of another object without redefining in order to create
well-defined class.”
“When creating a class, instead of writing completely new data
members and member functions, the programmer can designate that
the new class should inherit the members of an existing class.”
Shape.cpp Rectangle.cpp
//Base class //Derived class
class Shape{ class Rectangle:public Shape{
protected: public:
int width; int getArea(){
int height; return (width*height);
public: }
void setWidth(int w){ };
width=w;
} Main.cpp
void setHeight(int h){
height=h; //Main Program
} int main(){
}; Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
//Print the area of Rect
cout<<“Total area:”<<Rect.getArea();
return 0;
}
Polymorphism
Poly = many
Morph = form
Polymorphism - base class
class Shape destructor must be virtual
{
public:
virtual ~Shape ();
virtual void draw () = 0;
};
pure virtual (abstract) method
The destructor of a base class that is used in a polymorphic design must
be declared as virtual.

A pure virtual method has no implementation.


class Polygon{ class Triangle : public Polygon{
protected: public:
int width, height; int area(){
public: return (width*height/2);
void set_values(int a, int b){ }
width = a; }
height = b;
}
virtual int area() = 0; int main(){
}; Rectangle rect;
Triangle trg;
Polygon * poly1 = &rect;
class Rectangle : public Polygon{ Polygon * poly2 = &trg;
public: poly1->set_values(4,5);
int area(){ poly2->set_values(4,5);
return (width*height); cout<<poly1->area()<<“\n”;
} cout<<poly2->area()<<“\n”;
}; return 0;
}
Abstraction

Abstraction is an OOP design principle that is expressed in the concepts


and syntax of encapsulation and inheritance.
Abstraction
• The concept of abstraction relates to the idea of hiding data that is
not needed for presentation.
• It is to give a clear separation between properties of data type and
the associated implementation details.
• This separation is achieved in order that the properties of the
abstract data type are visible to the user interface and the
implementation details are hidden.
• Thus, abstraction forms the basic platform for the creation of user-
defined data types called objects.
Implement the interface concept
using pure virtual classes
A pure virtual class has
only pure virtual methods
class IHaveInventory
{
public:
virtual Item* find (string& name) = 0;
};
Understand new syntax:
pointers, references, and streams
Explicit pointer syntax:
choice between static and dynamic
static: object is automatically deleted
void function ()
{ when it goes out of scope
Student A;
string nameA = A.getName();
dynamic: memory allocated on heap
Student* B = new Student; must be explicitly deleted
string nameB = B->getName();
delete B;
}
References
void update_text (string& text)
{
text = “hi!”;
} reference to string object

[...] Why not use a pointer?


string my_string; my_string is modified
update_text (my_string);
cout << my_string << endl; prints hi!
Value, Reference, and Pointer
int a = 4; a is an integer
equal to the value 4

int& b = a; b is a reference to an integer


that refers to the variable a

int* c = &a; c is a pointer to an integer


equal to the address of a

int d = *c; d is an integer equal to


the value to which c points
Student a (“Rusell Alan Hulse”);

Student& b = a;

What is the fundamental


Student* c = &a; difference between the
last two lines of code?

Student* d = new Student(a);


Student& a; a is a reference to a Student

Student b;
&b; &b returns the memory
address of Student b

Student* c; c is a pointer to a Student

*c; *c is the Student object


to which c points
References Pointers
Type& ref = var; Type* ptr = new Type;

No need to dereference Must be dereferenced


Must be declared with value Can be initialized to NULL
Not suitable for arrays Single object or array of objects
Always refers to the same object Can be redirected to new object
Implicit temporary objects ok No implicit temporary objects
To smoothly transit from C#
use pointers to objects in C++
Any Questions?
Understand class syntax:
implicit methods
class MyClass
{
stream operators as friends (optional)
public:
default constructor
copy constructor Implicit
destructor Methods
assignment operator
other constructors
public methods
field access methods

private:
attributes (fields)
private methods
};
Implicit Methods
void function ()
{
MyClass A; Default Constructor

MyClass B (A); Copy Constructor

A = B; Assignment Operator

} Destructor (x 2)
The Standard C++ Library and
Standard Template Library
Everything in std namespace
#include <iostream>
[...]
std::cout << “Hello, World!” << std::endl;

OR
#include <iostream>
using namespace std;
[...]
cout << “Hello, World!” << endl;
Everything in std namespace
#include <string>
[...]
std::string name = “Anthony Hewish”;

OR
#include <string>
using namespace std;
[...]
string name = “Jocelyn Bell”;
C++ Basic I/O
C++ uses a convenient abstraction called streams to
perform input and output operations in sequential
media such as the screen, the keyboard or a file.

Standard output (cout)


Examples:
cout << “Hello World”; // prints Hello World on screen
cout <<120; //prints number 120 on screen
cout << x; // prints the value of x on screen

Standard input (cin)


Examples:
int age;
cin >> age;
Standard Template Library (STL)
#include <vector>
#include <string>
using namespace std;
[...]
// container class defined in STL
vector<string> names;
names.push_back(“Arno Allan Penzias”);
names.push_back(“Robert Woodrow Wilson”);
// vector class supports array notation
cout << names[0] << “ and “ << names[1];
Standard Template Library Concepts
Containers
• store elements of the template argument type
Algorithms
• common computational tasks performed on containers
• Allow initialization, sorting, searching, and transforming of the
contents of containers
Iterators
• independent access to container elements
• To step through the elements of collections of objects
#include <iostream>
#include <vector>
C++ Standard Template
using namespace std; (Vector Container)
int main(){
//create vector to store int
vector<int> vec;

//display the original size of vec


cout<<“Vector size=“<<vec.size()<<endl;

//push 5 values into the vector


for(int i=0; i<5; i++){
vec.push_back(i);
}

//display extended size of vec


cout<<“Extended vector size=“<<vec.size()<<endl;

//access 5 values from the vector


for(int i=0; i<5; i++){
cout<<“Value of vec[“<<i<<“]=“<<vec[i]<<endl;
}
//cont.. NEXT SLIDE
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while(v != vec.end()){
cout<<“Value of v = “<<*v<<endl;
v++;
}

return 0;
}
Let’s review the differences
C++ is a low level and indeed
platform neutral programming
language
C# is a high level language that is component oriented
C++ allows any type to be passed
by value, reference or pointer
C# does not have the concept of function pointers
In C++ the memory that is allocated
in the heap dynamically has to be
explicitly deleted
In C#, memory management is automatically handled by
garbage collector
In C++, the end of the class
definition has a closing brace
followed by a semicolon
In C#, the end of the class definition has a closing brace alone.
C++ does not contain for each
statement (only having for, while
and do…while)
In C#, has another flow control statement called for each
C++ uses stream operators
to simplify file I/O
C++ templates
are more flexible and powerful than
C# generics
Review the similarities
C++ supports encapsulation,
inheritance, polymorphism
(and abstraction)
C++ and C# share
syntax based on C
Enjoy programming in C++!
This Week’s Tasks
Supplementary Exercise: C++ Classes and Inheritance
Credit Task 2: Student Grading System (C++ Implementation)
Supplementary Exercise: Planetary Rover UML Class Diagram
Supplementary Exercise: Planetary Rover Code

You might also like