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

Lecture 2. Basics Part 1

This document describes a sample C++ program that uses a messaging class to display text. The messaging class has private member variables and public methods including accessor methods and constructors. The program defines the class and uses it in the main function to instantiate an object and call its methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lecture 2. Basics Part 1

This document describes a sample C++ program that uses a messaging class to display text. The messaging class has private member variables and public methods including accessor methods and constructors. The program defines the class and uses it in the main function to instantiate an object and call its methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Computer Methods 3

ENEL3CCH1
Week Two
A sample OOP application in C++

Discipline of Electrical, Electronic & Computer Engineering Bashan Naidoo


What we cover in week 2
A practical start - by example
• C++ class definition (Basic)
• Private member vars
• Public methods
• User defined methods
• Default constructor
• Overloaded constructor
• Accessor methods

• Instantiating an object of a class


• Initialising via constructor
• Using methods

• Console output via std::cout


• Declaring string variables
• Using namespaces and scope resolution
• Creating a namespace

• Core OOP concepts – some theory


Lets begin with a simple example
Description:

• C++ console application

• Uses a messaging class to display text on a the screen (standard output)

• Defines the messaging class and main program in one source file for now. Not good
practice in general, but useful for now. (Later we split them apart)

• Messaging class has private member variables and public methods. What is a
constructor?
• It includes accessor methods and constructors (default and overloaded constructor).

• In week 3 we add static members and a destructor to this class. What is a


constructor
overload?
#include <iostream>
Pre-processor
#include <string>
directives
class Message {
private:
std::string Msg;

public:
//Accessor methods
void setMsg(std::string Msg1) { this->Msg = Msg1; } We begin with
Class definition std::string getMsg() { return Msg; }
a complete
//Method solution in a
void display() { std::cout << Msg; } single file

//constructors
Message() { this->Msg = "Empty string!!!"; }
Message(std::string Msg) { this->Msg = Msg; }
};

int main(){
Message MsgObj("Howzit!"); //instantiate the object
Main program
MsgObj.display(); //use its method
return 0;
}
#include <iostream>
Pre-processor
#include <string>
directives
class Message {
private: Private section
std::string Msg; Contains private members
(usually data)
public:
//Accessor methods
void setMsg(std::string Msg1) { this->Msg = Msg1; } Public section
Class definition std::string getMsg() { return Msg; } Contains public members
(usually methods)
//Method
void display() { std::cout << Msg; } In this first example, the
methods are all defined
Default constructor //constructors (and implicitly declared)
Message() { this->Msg = "Empty string!!!"; } in the public section of
Message(std::string Msg) { this->Msg = Msg; } the class definition. This
Constructor overload }; is done for simplicity.
Uses overloaded constructor
int main(){
Message MsgObj("Howzit!"); //instantiate the object
Main program
MsgObj.display(); //use its method
return 0;
}
main() cannot see Msg, or access it directly. It is private.
#include <iostream>
Pre-processor
#include <string> However, main() can do the following…
directives • read/modify Msg via public accessor methods, and
• Modify Msg via the public overloaded constructor
class Message {
private: Private section
std::string Msg; Contains private members
(usually data)
public:
Discussion: //Accessor methods
void setMsg(std::string Msg1) { this->Msg = Msg1; } Public section
Why bother having accessor std::string getMsg() { return Msg; }
Classwhen
methods, definition
we can just Contains public members
make all members public? (usually methods)
//Method
What is the potential void display() { std::cout << Msg; } In this first example, the
benefit of accesors? methods are all defined
//constructors (and implicitly declared)
Message() { this->Msg = "Empty string!!!"; } in the public section of
Message(std::string Msg) { this->Msg = Msg; } the class definition. This
Overloaded constructor }; is done for simplicity.

int main(){
Message MsgObj("Howzit!"); //instantiate the object
Main program
MsgObj.display(); //use its method
return 0; main() modifies Msg via the public
} overloaded constructor at instantiation
#include <iostream>
Pre-processor
#include <string> We now proceed to a formal
directives
separation of code into
class Message { different files. This has
private: advangates. Can you
std::string Msg; identify an advantage? Firstly, we want to
explicitly declare all
public: the public members in
//Accessor methods the public section of
void setMsg(std::string Msg1) { this->Msg = Msg1; } the class up here.
Class definition std::string getMsg() { return Msg; }

//Method
void display() { std::cout << Msg; }

//constructors
Message() { this->Msg = "Empty string!!!"; }
Message(std::string Msg) { this->Msg = Msg; } Then we want our
}; public member
definitions down
here, and we
scope these back
into the class.
int main(){
Message MsgObj("Howzit!"); //instantiate the object
Main program
MsgObj.display(); //use its method
#include <iostream>
#include <string> class Message {
private:
std::string Msg;

public:
void setMsg(std::string Msg1);
Explicit method
std::string getMsg(); declarations
void display(); (prototypes)
Message(); //default constructor
Message(std::string); //construct overload
};

void Message::setMsg(std::string Msg1) { this->Msg = Msg1; } We have separated


std::string Message::getMsg() { return Msg; } method declaration
and definion.
void Message::display() { Next, we split the
Method std::cout << Msg;
}
code into three files…
definitions
…outside, but Message::Message() { //define default constructor
still in class this->Msg = "Empty string!!!";
scope }

Message::Message(std::string Msg) {
this->Msg = Msg;
int main(){
}
Message MsgObj("Howzit!"); //instantiate the object
MsgObj.display(); //use its method
return 0;
}
MyProg.cpp
#include <iostream> We have separated
#include <string>
#include “Message.h” the files, but for
#pragma once int main(){
them to work
and header Message MsgObj("Howzit!"); //instantiate the object together, additional
guards will be MsgObj.display(); //use its method preprocessor
discussed later… return 0; directives are needed
}

Message.h Message.cpp
Class header file #include “Message.h”
#pragma once
#include <iostream> Declares the class
#include <string> void Message::setMsg(std::string Msg1) { this->Msg = Msg1; }
interface… everything
the caller needs to
class Message { std::string Message::getMsg() { return Msg; }
know about the class
private:
std::string Msg; void Message::display() {
std::cout << Msg;
public: }
void setMsg(std::string Msg1);
std::string getMsg(); Message::Message() { //define default constructor
void display(); this->Msg = "Empty string!!!";
Class implementation file
Message(); //default constructor }
Message(std::string); //construct overload Contains method
}; Message::Message(std::string Msg) { implementations for the class
this->Msg = Msg; The caller does not need to
} know this stuff
Intro to Namespaces
• A feature added to C++
• Does not exist in C

A spatial A sense of
grouping belonging

A declarative region that provides scope to the


identifiers defined inside it.
Types,
variables,
functions
Namespaces – example 1
#include <iostream>//needed if you are using std::cout etc.
#include <string>//needed if you are defining std::string variables

namespace BN { //illustration of a user defined namespace


std::string endl() { return "\n"; }
} Two functions have the same name, but
resolve to different namespaces – so
there is no confusion. The fully resolved
int main(){ targets are different
std::cout << "Hello World!\n";
std::cout << "Hello KZN!" << BN::endl(); //uses endl from BN
std::cout << "Hello Durban!" <<std::endl; //uses endl from std
}
Namespaces – example 1
#include <iostream>//needed if you are using std::cout etc.
This is the
#include <string>//needed if you are defining std::string variables
function I
want
namespace BN { //illustration of a user defined namespace
std::string endl() { return "\n"; }
}
std::cout << "Hello KZN!" << BN::endl();
int main(){
std::cout << "Hello World!\n"; This is where
std::cout << "Hello KZN!" << BN::endl(); //uses endl from
to find it BN
std::cout << "Hello Durban!" <<std::endl; //uses endl from std
}
Namespaces – example 1
namespace std namespace BN

:
namespace BN { //illustration of a user defined namespace
string std::string endl() { return "\n"; }
cout }
endl
:

Source file

int main(){
std::cout << "Hello World!\n";
std::cout << "Hello KZN!" << BN::endl(); //uses endl from BN
std::cout << "Hello Durban!" <<std::endl; //uses endl from std
}
Namespaces – example 1
Source file namespace BN

:
string
cout namespace BN { //illustration of a user defined namespace
endl std::string endl() { return "\n"; }
: }

“using namespace std”


effectively brings that entire
“std” namespace into source
file scope. So we don’t have
to specify std::
I still have to fully
specify BN::endl()
using namespace std;

int main(){
cout << "Hello World!\n";
cout << "Hello KZN!" << BN::endl(); //uses endl from BN
cout << "Hello Durban!" << endl; //uses endl from std
}
Namespaces – example 1
Source file

We now have one


unified namespace like
namespace BN { //illustration of a user defined namespace in ANSI-C, and we can
std::string endl() { return "\n"; }
} no longer resolve the
difference between the
using namespace BN; two endl functions
using namespace std;

int main(){
cout << "Hello World!\n";
cout << "Hello KZN!" << endl(); //uses endl from BN
cout << "Hello Durban!" << endl; //uses endl from std
}

Confusion here!!!
Now we have seen by example that…

A defined
approach OOP is not a language A way of
thinking

OOP is a methodology
A system of
OBJECTs principles

are central to OOP


What is OOP?
One must understand the philosophical basis of OOP before the
its syntactical expression in C++.

Philosophical
Abstraction concepts Inheritance

Polymorphism

Encapsulation Object

Class
Abstraction
A key concept in OOP (but not limited to OOP)

Abstraction is the process of hiding detail, while retaining the meaning

Main goal: Reduce complexity by hiding low-level detail

For example: In a report, the abstract represents only the essential


features without including the background details or explanations.
Encapsulation
The most fundamental concept of OOP…

Main goal: To enclose data and methods that work on the data, in
one unit
Single unit
Class definition
Data
Member variables

Methods Member functions


Object
An Object is an identifiable entity

with defined

Data Methods
characteristics and behaviour.

Member Member
variables? functions?
Class
So you can say…
Each of these related
objects is an instance
of that class

A Class is a group of related objects that have…


common properties and methods.
So, when we analyse the problem; we
don’t only identify disconnected objects…
Note: Don’t confuse a
we identify objects of a class. Class with a Class
That is… multiple objects of a particular definition.
class.
Class

As far as possible,
Identify classes so that they follow the…

Single responsibility principle


• Where the class is focused on a clear single concern.
• This makes the class more robust.
• This makes the class easier to maintain.
Class

As far as possible,
Identify classes so that they follow the…

Open-Closed principle
• Where the class is open for extension, but closed for modification.
• This allows you to add new functionality (by extension) without
changing existing code (modification).
• This makes the class easier to maintain.
Inheritance

The ability of one class of objects…


to acquire capabilities or properties from other classes.

We will consider this topic later


Polymorphism
The word polymorphism means having many forms

Generally, polymorphism occurs when there is a hierarchy of the


classes and they are related by the inheritance.

You need to understand inheritance first


We will consider this topic later
ABC of learning
When do you become an Engineer? When you are able to…
Values
Emotions Attitudes
Feelings

• Feel like and engineer should feel (Affective learning)

Respectful
Confident
• Behave like and engineer should behave (Behavioural learning) Focused
Skilled

• Think like an engineer should think (Cognitive learning)


Competent
Knowledgeable
Understanding
Innovative
Let us extend the OOP demo
• Add static member vars
These are common to all instances of the class; so if one object modifies a static var, all other instances of that
class will see the change. It is a shared resource.

For example:
Use this to count the total number of messages sent by all instances of the class
Or use this to count the number of class instances currently in existence

• Add static member functions


These can only access static member vars.

For example:
Use this to print the total number of messages sent by all instances of the class
Or to print the total number of class instances in existence

• Add a destructor
that indicates the destruction of an object and the number of class instances
still left.

You might also like