SystemC-n-BehaviorCoding_Fall2021_Section3_C++
SystemC-n-BehaviorCoding_Fall2021_Section3_C++
Section 3
C++, The Object Oriented C
3-1 Introduction and Basics
C++
The object oriented C
Class
Data members
Access methods a.k.a member functions
Inheritance
Template
Virtual function
Not “English as
Second Language”
Drag picture to plac
Object Oriented
4
+ 5
Object
Controlling assert()
Constructor
Creates the instance and construct it
Function name is the class name, no return type
specifying needed, since the return must be the
class itself
Default constructor has no any input parameters.
It is by default called when a class is ‘instantiated’
Can have multiple constructors, with different
input parameters for different usage. The compiler
will resolve which constructor to use by matching
exact input parameters and types
No return statement
+ 8
Constructor Examples
// default constructor is not a must, but for the sake of
// coding discipline, it is best to code it anyway
List::List() {
_Length = 0;
_Array = NULL;
}
Copy Constructor
Needed when
a class object is passed to a function via a value parameter;
a function returns a class object as its return value; and
the result of a sub-expression is a class object that must be
held temporarily, until the result of another sub-expression
has been computed
// Copy constructor
List::List(const List& org) {
_Length = org._Length;
if (_Length > 0) {
_Array = new int [_Length];
assert(_Array != 0);
for (int i = 0; i < _Length; i++)
_Array[i] = org._Array[i];
}
else
_Array = NULL;
}
+ 11
Assignment Operator
// Assignment operator
List& List::operator=(const List& org) {
if (this != &org) { // if the same one, do nothing
delete [] _Array; // _Array may not be NULL
_Length = org._Length;
if (_Length > 0) {
_Array = new int [_Length];
assert(_Array != 0);
for (int i = 0; i < _Length; i++)
_Array[i] = org._Array[i];
}
else
_Array = NULL;
}
Deconstructor
Deconstructor – An Example
// deconstructor
List::~List() {
if (_Length != 0) {
delete [] _Array;
_Array = NULL;
_Length = 0;
}
}
+ 15
Member Function
// declaration in List.h
int setElement(unsigned int, int);
// implementation in List.cpp
int List::setElement(unsigned int pos,
int val) {
if (pos < _Size)
return _Array[pos];
}
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
Namespaces
1
6
+ 17
namespace
namespace identifier {
entities
}
where identifier is any valid identifier, and entities are
classes, variables and functions in the namespace
+ 18
namespace Example 1:
Resolution
#include <iostream> Result
// std is a namespace too 5
using namespace std; 3.14159
namespace first {
int var = 5;
}
namespace second {
double var = 3.14159;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
+ 19
int main () {
using first::x;
using second::y;
cout << x << endl;
cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
return 0;
}
+ 20
namespace second {
double x = 3.14159;
double y = 1.83729;
}
int main () {
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return 0;
}
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
I/O Stream
2
1
+ 22
std Namespace
#include <iostream>
#include <fstream>
Basic Operators
<< - output operator
>> - input operator
endl – new line, “\n”
Examples
cout << “Got to run!” << endl;
cin >> inStr;
+ 24
Example
fstream oFile, iFile;
int inInt;
iFile.open(“input”, ios::in);
oFile.open(“output”, ios::app);
if (!iFile.fail())
while(!iFile.eof()) {
iFile >> inInt;
oFile << inInt << endl;
}
oFile.close();
iFile.close()
}
+ 26
Output Formatting
Manipulators
setw(width) – display the next value in a field with the
specified width (1 is default)
setprecision(precision) – display values with the
specified precision (6 is common default)
setiosflags(flagList) – set the formatting flags, where
flagList is a sequence of one or more flags, separated
with the | operator, where flags are
ios::showpoint – display decimal point and trailing 0’s
ios::fixed – display real values in fixed-point
ios::scientific – display real values in floating-point
ios::left – display values left-justified within a field
ios:right – display values right-justified within a field
+ 27
Output is:
(2.666667)
(3)
(2.66667)
(3.00000)
(2.667)
( 3.000)
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
Operator
Overloading
2
8
+ 29
Assignment Operator
return *this;
}
+ 30
operator+ Overloading
+ is a binary operator. However its operation is to evaluate, then
the class returned is used to update. This is a member function of
the class, so class resolution is needed
Its return type cannot be a reference, i.e. &
// implementation
List List::operator+(const List &other) {
unsigned int loop =
_Size < other._Size ? _Size:other._Size;
// create a return object is required
List lt(loop);
for (int i = 0; i < loop; i++) {
lt._Array[i] = _Array[i] + other._Array[i];
return lt;
}
+ 31
operator+= Overloading
+= is a unary operator. However its operation is to evaluate, then the
class returned is used to update. This is a member function of the
class, so class resolution is needed
Its return type can either referenced or not, i.e. & or no &
// implementation
List List::operator+=(const List &other) {
unsigned int loop =
_Size < other._Size ?
_Size:other._Size;
for (int i = 0; i < loop; i++) {
_Array[i] += other._Array[i];
return *this;
}
+ 32
operator++() Overloading
++ is a unary operator. However there are two forms of this
operator, prefix and postfix. operator++(), or operator++
(void), are used for prefix, e.g. ++list
Its return type can either referenced or not, i.e. & or no &
// implementation
List List::operator++() {
for (int i = 0; i < _Size; i++) {
++_Array[i]; // prefix ++
return *this;
}
+ 33
operator++(int) Overloading
// implementation
List List::operator++(int) {
List tmp(*this); // Retain a copy first
for (int i = 0; i < _Size; i++) {
_Array[i]++; // postfix++
return tmp;
}
+ 34
operator<< Overloading
// implementation
ostream& operator<<(ostream &out, List list) {
for (int i = 0; i < list._Size; i++)
out << list._Array[i] << “ “;
out << endl;
return out;
}
+ 35
operator>> Overloading
>>,the input operator, can be overloaded as in the following
example. Note that it is a friend class to istream so no class
resolution, ::, needed
// implementation
istream& operator>>(istream &in, List &list)
{
for (int i = 0; i < list._Size; i++)
in >> list._Array[i];
return in;
}
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
Inheritance
3
6
+
What is Inheritance?
Take the chair for example. There are many different types
of chairs: arm chair, wheel chair, bench, stool, etc.
But they all have two elements: seat and leg(s), and one
function: sit
So we can have a base chair/class with above data member
and member function, then derive all different types of
chairs/classes. This derivation, is thus the property of
inheritance
3
7
+ 38
Encapsulation
The purpose is to control who can do what, with following three
keywords:
public
Accessible inside and outside of this class
Usually we make member functions public
But you can make private functions as well
private
Accessible inside of this class only
Usually we make data members private
protected
Accessible by this class, its friend classes, and derived classes
Base Class
Abase class holds the common properties (data member and
member functions)
class Employee {
private:
string name;
string id;
double net_pay;
public:
Employee();
Employee(string _name, string _id);
string get_name();
string get_id();
double get_net_pay();
void set_name(string _name);
void set_id(string _id);
void set_net_pay(double _net_pay);
void print_check();
};
+ 40
string Employee::get_name() {
return name;
}
string Employee::get_id() {
return id;
}
double Employee::get_netPay() {
return netPay;
}
+ 41
void Employee::print_check() {
cout << "\nError: print_check function called for"
<< " a undefferentiated employee.\n"
<< " Program aborted\n";
exit(1);
}
+ 42
Derived Class I
And a derived class extends properties of the base
class
#ifndef HOURLYEMPLOYEE
#define HOURLYEMPLOYEE
#include <string>
#include "Employee.h“
using namespace std;
#endif
+ 43
double HourlyEmployee::get_hours() {
return hours;
}
void HourlyEmployee::print_check() {
set_netPay(hours * wageRate);
Derived Class II
#ifndef SALARIEDEMPLOYEE
#define SALARIEDEMPLOYEE
#include <string>
#include "Employee.h"
public:
SalariedEmployee();
SalariedEmployee(string _name, string _id,
double _salary);
void set_salary(double _salary);
double get_salary();
void print_check();
};
#endif
+ 46
double SalariedEmployee::get_salary() {
return salary;
}
void SalariedEmployee::print_check() {
set_netPay(salary);
Not “English as
Second Language”
Drag picture to plac
Template
4
8
+
Why Template?
4
9
+ 50
tmp = var1;
var1 = var2;
var2 = tmp;
}
+ 51
tmp = var1;
var1 = var2;
var2 = tmp;
}
+ 52
template<class T>
void swapVal(T &var1, T &var2) {
T tmp;
tmp = var1;
var1 = var2;
var2 = tmp;
}
+ 53
Using Template
#include <iostream>
#include "swapVal.h"
#include <iostream>
#include <cstdlib>
public:
Pair();
Pair(Tmplt firstVal, Tmplt secondVal);
// intentionally use automatic de-constructor creation
template<class T>
void Pair<T>::setElement(int pos, T val) {
if (pos == 0)
first = val;
else if (pos == 1)
second = val;
else {
cout << "Error: Illegal pair position\n";
exit(1);
}
}
+ 56
template<class T>
T Pair<T>::getElement(int pos) {
if (pos == 0)
return first;
else if (pos == 1)
return second;
else {
cout << "Error: Illegal pair position\n";
exit(1);
}
}
+ 57
return 0;
}
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
Virtual Function
5
8
+ 59
#ifndef ANIMAL
#define ANIMAL
#include <string>
class Animal {
private:
string kind;
public:
Animal();
Animal(string _kind);
string getKind();
virtual void say();
};
#endif
+ 61
Animal::Animal() {
kind = "";
}
Animal::Animal(string _kind) {
kind = _kind;
}
string Animal::getKind() {
return kind;
}
void Animal::say() {
cout << "Not any known animal, say nothing\n";
return;
}
+ 62
#include "Animal.h"
Dog::Dog() : Animal("Dog") {
}
void Dog::say() {
cout << getKind() << " barks\n";
return;
}
+ 64
#ifndef WOLF
#define WOLF
#include “Dog.h"
Wolf::Wolf() : Dog(“Wolf") {
}
void Wolf::say() {
cout << getKind() << " woos\n";
return;
}
+ 66
Wolf::Wolf() : Dog(“Wolf") {
}
void Wolf::say() {
cout << getKind() << " woos\n";
return;
}
+ 67
return 0;
}
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
make
6
8
+ 69
What Is make?
Example
Take the Animal classes as and example, we need to compile Animal.cpp,
Dog.cpp, Wolf.cpp and main.cpp then link into an executable
CC = g++
SRC = Animal.cpp Dog.cpp Wolf.cpp
OBJ = ${SRC:.cpp=.o} main.o
TARGET = animal
all: $(TARGET)
Tab Animal.o: Animal.h Animal.cpp
$(CC) -c Animal.cpp
Dog.o: Dog.h Dog.cpp
$(CC) -c Dog.cpp
Wolf.o: Wolf.h Wolf.cpp
$(CC) -c Wolf.cpp
main.o: main.cpp
$(CC) -c main.cpp
$(TARGET): $(OBJ)
$(CC) $(OBJ) -o $@
clean:
rm *.o
rm $(TARGET)
+ 71
Assignment 3 makefile
CC = g++
PCFLAG = -O1 -Wall -c
POFLAG = -O1 -Wall
HDR = Array.h List.h
SRC = ${HDR:.h=.cpp} main.cpp
OBJ = ${HDR:.h=.o} main.o
TARGET = list
all: $(TARGET)
Array.o: Array.h Array.cpp
$(CC) $(PCFLAG) $(@:.o=.cpp)
List.o: List.h List.cpp
$(CC) $(PCFLAG) $(@:.o=.cpp)
main.o: main.cpp
$(CC) $(PCFLAG) $(@:.o=.cpp)
$(TARGET): $(OBJ)
$(CC) $(POFLAG) $(LIB) $(OBJ) -o $@
clean:
rm $(OBJ)
rm $(TARGET)
+
Drag picture to placeholder or click ico
Not “English as
Second Language”
Drag picture to plac
7
2
+
Core Dump & gdb
74