0% found this document useful (0 votes)
47 views72 pages

C++ Structures and Classes Overview

The document provides an overview of C++ programming concepts, focusing on structures, classes, and object-oriented programming principles. It covers member access, function parameters, static vs non-static members, constructors, destructors, and inheritance. Additionally, it discusses the organization of code into header and implementation files for better structure and maintainability.

Uploaded by

Infinite Primus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views72 pages

C++ Structures and Classes Overview

The document provides an overview of C++ programming concepts, focusing on structures, classes, and object-oriented programming principles. It covers member access, function parameters, static vs non-static members, constructors, destructors, and inheritance. Additionally, it discusses the organization of code into header and implementation files for better structure and maintainability.

Uploaded by

Infinite Primus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

1

CSC230

Intro to C++ (Part 2)


Structure
2

array:
• User defines
• Combine multiple data items of same type

structure:
• User defines
• Combine multiple data items of different types

struct TCNJstudent Structure tag (optional)


{
char name[50];
char major[50]; Member definition
char homeAddress[100];
int id;
}csStudent, mathStudent; Structure variable(s)
Access members of a structure
3

include <iostream>
#include <string>
using namespace std;

struct TCNJstudent
{
char name[50];
char major[50];
char homeAddress[100];
int id;
};

TCNJstudent immStudent;

int main () Structure variables


{ Member access
TCNJstudent csStudent, mathStudent;
csStudent.id = 1000;
mathStudent.id = 2000;
strcpy(csStudent.name, "Mike Lee");
strcpy(csStudent.major, "CS");
strcpy(csStudent.homeAddress, "Earth");
cout << csStudent.name << " " << csStudent.homeAddress <<endl;
Structure as a function parameter
4

struct TCNJstudent
{
char name[50];
char major[50];
char homeAddress[100];
int id;
};

void infoCheck(TCNJstudent student)


{
cout << student.name << endl;
}

infoCheck(csStudent);
Pointers to structures
5

struct TCNJstudent
{
char name[50];
char major[50];
char homeAddress[100];
int id;
};

void infoCheck(TCNJstudent *student)


{
cout << student->name << endl;
}

infoCheck(&csStudent);
Class and Object
6

class Base { • Access specifiers: public, private,


protected
public: • Each class may have multiple
sections
// public members go here • Each section remains effective
until either another section or the
protected: end of the class body
• The default access is private
// protected members go here

private:

// private members go here

};
Class and object example
7

#include <iostream>
#include <string>
using namespace std;

class student
{
public:
char name[50];
char major[50];
char homeAddress[100];
};

int main ()
{
student csStudent, mathStudent;
strcpy(csStudent.name, "Mike Lee");
strcpy(csStudent.major, "CS");
strcpy(csStudent.homeAddress, "Earth");
cout << csStudent.name << " " << csStudent.homeAddress <<endl;
return 0;
}
Method definition
8

class employee class employee


{ {
public: public:
... ...
int id; int id;
declaration
int getID(){ int getID();
return id; };
definition
}
}; int employee::getID(){
return id;
}

scope operator

✔ ✔
Static vs. Non-static
9

non-static data member


Each object has its own copy
employee s1;
static data member employee s2;
One copy per class type, e.g. counter employee s3;

class employee
{
public: count
...
int id;
static int counter; s1 s2
int getID(){ … …
return id; id id
}
}; …
s3 id
Const method/member function
10

 const method/member function


 declaration
 return_type func_name (para_list) const;
 definition
 return_type func_name (para_list) const { … }
 return_type class_name :: func_name (para_list) const { … }
 It is illegal for a const member function to modify a class
data member
Const Member Function
11

class student
{
private :
function declaration
string name, addr, major;
public :
void info() const;
function definition
};

void student:: info( ) const


{
cout << name << “:” << addr << “:” << major << endl;
}
TCNJstudent class
12

class TCNJstudent
{
private:
char name[50];
char major[50];
int id;
public:
void setName();
void setMajor();
TCNJstudent(); // constructor
void info() const;
};
Class Interface
13

TCNJstudent class

setName
Private data:
setMajor
name

major
TCNJstudent id

info
Access specifier
14

Access From Public Protected Private


Same class Yes Yes Yes
Derived classes Yes Yes No
Everywhere Yes No No

• The default access specifier is private.


• The data members are usually private or protected. A private member can be accessed
by another member function of the same class (exception friend function, more
details later)
• Each access control section is optional, repeatable, and sections may occur in any
order
One more example
15

#include <iostream> // member function definitions


class circle void circle::store(double r)
{ {
private: radius = r;
double radius; }
public:
void store(double);
double circle::area(void)
double area(void);{
void display(void);return 3.14*radius*radius;
}; }

void circle::display(void)
{
std::cout << "r = " << radius << std::endl;
}
int main(void) {
circle c; // an object of circle class
c.store(5.0);
std::cout << "The area of circle c is " << c.area() << std::endl;
c.display();
}
Look inside the example
16

int main(void) {
circle c; // an object of circle class
c.store(5.0);
std::cout << "The area of circle c is " << c.area() << std::endl;
c.display();
}

c is statically allocated endl is defined in std namespace


Does this one work?
17

int main(void) {
circle c, *d;
d.store(5.0);
std::cout << "The area of circle c is " << d.area() << std::endl;
d.display();
}
Does this one work?
18

int main(void) {
circle c, *d;
d.store(5.0);
std::cout << "The area of circle c is " << d.area() << std::endl;
d.display();
}

• d is a pointer, which should have the address of someone in the memory.


• Did we initialize d ? NO!
• Did compile initialize it? NO!
First modification
19

int main(void) {
circle c, *d;
d = &c;
d.store(5.0);
std::cout << "The area of circle c is " << d.area() << std::endl;
d.display();
}

• d is initialized
• d is a pointer, we cannot use d.store(), d.area(), d.display() to access the functions.
Second modification
20

int main(void) {
circle c, *d;
d = &c;
d->store(5.0);
std::cout << "The area of circle c is " << d->area() << std::endl;
d->display();
}


Pointer, dynamic memory
21

d is dynamically allocated

int main(void) {
circle *d;
d = new circle();
d->store(5.0);
std::cout << "The area of circle c is " << d->area() << std::endl;
d->display();
}
More example of dynamic memory
22

d and e are dynamically allocated

int main(void) {
circle *d;
d = new circle();
int * e = new int[15];
d->store(5.0);
std::cout << "The area of circle c is " << d->area() << std::endl;
d->display();
delete d;
delete[] e;
}

Memory of d and e are released back to the system

delete release one element


delete [] release one array
You need to call delete or delete [] as many times you called new or new [] respectively.
Object initialization
23

int main(void) {
circle *d;
d = new circle();
d->set(5.0);

circle c;
c.set(4.0);
}
Object initialization, Constructor
24

class circle
{
private:
double radius;

public: • Default constructor


void set(double r); • Copy constructor
circle();
circle(const circle &r); • Constructor with parameters
circle(double r);
};
• Publicly accessible
• same name as the class
• no return type
• to initialize class data members
• different signatures
Object initialization, Constructor
25

class circle
When a class is declared with no
{ constructors,
private: the compiler automatically assumes default
double radius; constructor and copy constructor for it.
• Default constructor
public:
void set(double r);
}; circle:: circle() { };

• Copy constructor

circle:: circle (const circle & r)


{
radius = r.radius;
};
Object initialization, Constructor
26

• Initialize with default constructor


class circle
{
private: circle r1;
double radius; circle *r2 = new circle();

public:
void set(double r);
}; • Initialize with copy constructor

circle r3; //default


If no customer defined constructors. r3.set(5.0);
C++ provides default constructors
and copy constructor. circle r4 = r3; //copy
circle r5(r4); //copy

circle *r6 = new circle(r4); //copy


Object initialization, Constructor
27

class circle
{
If any constructor is declared,
public: • no default constructor will exist,
double radius; unless you define it.
• still have copy constructor
public:


void set(double r);
circle r1;
circle(double r){radius = r;}

};
• Initialize with constructor
circle r1(5.0);
circle *r2 = new circle(6.0);


Constructor and destructor
28

An object can be initialized by


• Default constructor
• Copy constructor
• Constructor with parameters

When the object is initialized, resources are allocated.

Just before the object is terminated, the allocated resources should


be returned to system.
Destructor
29

class account destructor:


{ • Its name is class name preceded by ~
private: • No argument
char *name;
• Release dynamic memory and cleanup
double balance;
unsigned int id;
• Automatically executed before object goes
out of scope, or when delete a pointer to a object.
public:
account();
account(const account &c);
account(const char *d);
~account();
} Destructor declaration

account::~account()
{
Destructor definition
delete[] name;
} Delete whole string.

delete name; Delete one char.


Work with multiple files
30

A set of .cpp and .h files for each class group


• .h file contains the prototype of the class
• .cpp contains the implementation of the class

A .cpp file containing the main() function should include all the corresponding .h
files where the functions used in .cpp file are declared.
Example: TCNJstudent.h
31

class TCNJstudent
{
private:
char name[50];
char major[50];
int id;
public:
void setName();
void setMajor();
TCNJstudent();
void info() const;
};
Example: TCNJstudent.cpp
32

#include <iostream>
Assume the implementation needs this file
#include <string>
#include "TCNJstudent.h"
using namespace std; Must include the corresponding
header file
void TCNJstudent::setName()
{…
} To simplify the example, we use blank body.
void TCNJstudent::setMajor() A real implementation can have various
{… body.
}
TCNJstudent::TCNJstudent()
{…
}
void TCNJstudent::info()
{…
}
Example: main.cpp
33

#include "TCNJstudent.h"
Must include the corresponding header file
int main(){

}

Compile
g++ -o excuFile main.cpp TCNJstudent.cpp

Any executable filename you prefer


Separate Compilation and Linking of Files
34

specification file
main program TCNJstudent.h implementation file
main.cpp TCNJstudent.cpp
#include “TCNJstudent.h”

Compiler Compiler

main.o TCNJstudent.o

Linker

execFile
Inheritance
35

Polygon
class Polygon{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int nV);
};
Triangle

Rectangle class Triangle{


private:
int numVertices;
class Rectangle{ float *xCoord, *yCoord;
private: public:
int numVertices; void set(float *x, float *y, int nV);
float *xCoord, *yCoord; float area();
public: };
void set(float *x, float *y, int nV);
float area();
};
Inheritance
36

Polygon class Polygon{


protected:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int nV);
};
Rectangle
Triangle
class Rectangle{
protected:
class Rectangle : public Polygon{ int numVertices;
public: float *xCoord, *yCoord;
float area(); public:
}; void set(float *x, float *y, int nV);
float area();
};
Inheritance
37

Polygon class Polygon{


protected:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int nV);
};
Rectangle
Triangle
class Triangle{
protected:
class Triangle : public Polygon{ int numVertices;
public: float *xCoord, *yCoord;
float area(); public:
}; void set(float *x, float *y, int nV);
float area();
};
Base & Derived Classes
38

 Syntax:
class derived-class : access-specifier base-class
where
 access-specifier is one of public, protected, or private

 private by default
 Most of the time, people use public

 Any class can serve as a base class


 Thus a derived class can also be a base class
Class hierarchy
39

class Point{
point protected:
int x, y;
public:
void set (int a, int b);
};
circle
class circle : public point{
private:
double r;
cylinder ... ...
};

class cylinder : public circle{


private:
double h;
... ...
};
What to inherit?
40

 In principle, every member of a base class is


inherited by a derived class
 just with different access permission
Access control over the members
41

Base
class/superc How to decide the access specifiers of the
lass/parent members in the subclass?
class
• Class definition
Members go to

• Inheritance type
Derive from

class Polygon{
protected:
int numVertices;
float *xCoord, *yCoord;
public:
Derived void set(float *x, float *y, int nV);
class/subclass/ };
child class

class Triangle : public Polygon{


public:
float area();
};
Access specifier of derived class
42

class derived-class : access-specifier base-class

Type of Inheritance
of superclass member
Access specifier

Public Protected Private


Public Public Protected Private
Protected Protected Protected Private
Private - - -

 The type of inheritance defines the access level for the


members of derived class that are inherited from the base
class
Private member access
43

#include <iostream> Private member in superclass


using namespace std;

class father{
private: int fPrv;
protected:
int getPrivateValue(){ A protected function access the private member
return fPrv;
}
};

class son: public father{


public: The protected function is inherited
int foo(){
return getPrivateValue();
}


};

int main(){
son obj;
cout<<obj.foo()<<endl;
cout<<obj.fPrv<<endl;
}
What is inherited?
44

• In general, every member of a base class is inherited by a derived class, even


the private ones.
• The private member from base class is not directly accessible to the
derived class. It must be through a public/protected method from the base
class.

• Some exceptions:
• Constructor and destructor
• Operator=() member
• Friends

These functions are class-specific


Rules for constructor/destructor in derived class
45

Without explicit specification, the default constructor and destructor of the base class
will be called first when a new object of the derived class is created or destroyed.
class A{
public:
A(){
cout<< "A: default constructor"<<endl; When B(int a)is executed, A() will
} be executed first.
A(int a){
cout<<"A: with a"<<endl;
}
} If there is a statement in the main():

class B:public A{ B obj(1);


public:
B(int a){
cout<<"B: with a"<<endl;
The output will be:
}
} A: default constructor
B: with a
Rules for constructor/destructor in derived class
46

The constructor and destructor of the derived class can specify which
constructor/destructor should be invoked.
class A{
public:
A(){
cout<< "A: default constructor"<<endl;
}
A(int a){
cout<<"A: with a"<<endl;
}
} If there is a statement in the main():

class B:public A{ B obj(1);


public:
B(int a) : A(a){
cout<<"B: with a"<<endl;
The output will be:
}
} A: whit a
B: with a
overloading
47

void PrintMe (string s) {


cout << "string s = \"" << s << "\"" << endl ;
}

void PrintMe (int i) {


cout << "int i = " << i << endl ;
}
Overriding
48

class A {
protected:
int x, y; Method in parent class
public:
void print ()
{cout<<"From A"<<endl;}
};

class B : public A {
public: Method in child class with same signature
void print ()
{cout<<"From B"<<endl;}
};
Overriding
49

class A {
protected:
int x, y;
public:
void print ()
{cout<<"From A"<<endl;}
};

class B : public A {
public:
void print ()
{ Call the print() in A class
A::print(); NO super keyword in C++
cout<<"From B"<<endl;
}
};
this pointer in C++
50

class test{ class test{


private: How can we access private:
int x; it from member int x;
public: function? public:
void setX(int x){ void setX(int x){
x = x; this->x = x;
} }
}; };

parameter this pointer has the


address the current
object

Given a object, each member function of this object has a implicit parameter of this, only
member function has this. Friend functions don’t have it.
A review of inheritance
51

 TCNJstudent: base class


 CSstudent : the derived class with
TCNJstudent
public inheritance
 A derived class can
 inherit all members from the base
class, except the constructor
 access all public and protected
CSstudent members of the base class
 define its own data member
 provide its own constructor
 define its own member functions
 override functions inherited from the
base class
TCNJstudent.h
52

#include <string>
using namespace std;
class TCNJstudent
{
private:
string name;
string major;
int id;
public:
void setName(string a);
void setMajor(string a);
TCNJstudent();
void info() const;
};
TCNJstudent.cpp
53

#include <iostream>
#include <string> void TCNJstudent::info()
#include "TCNJstudent.h" {…
using namespace std;
}
void TCNJstudent::setName(string a)
{…
}

void TCNJstudent::setMajor(string a)
{
name = a;
}

TCNJstudent::TCNJstudent()
{…
}
CSstudent.h
54
Parent class
#include "TCNJstudent.h" declaration
#include <string>
using namespace std;

class CSstudent : public TCNJstudent


{
private:
bool likeGame;
public:
CSstudent();
CSstudent(string a, string b, string c);
void setMajor();
};
CSstudent.cpp
55

#include <iostream>
#include "CSstudent.h"

void CSstudent::setMajor(){
TCNJstudent::setMajor("CS");
}

CSstudent::CSstudent(){
cout <<"From CSstudent()"<<endl;
}

CSstudent::CSstudent(string a, string b, string c){


cout<< "From CSstudent(a, b, c)" << endl;
}
main.cpp
56

#include "CSstudent.h"

int main(){
CSstudent stu;
stu.setMajor();
CSstudent stu2("Mike", "CS", "NJ");
}

Compile
g++ -o excuFile main.cpp TCNJstudent.cpp CSstudent.cpp
Class Interface
57

CSstudent class Private data:


likeGame

setName setName
Private data:
setMajor setMajor
name

CSstudent TCNJstudent major

id
CSstudent info

info
Polymorphism
58

Polymorphism:
• Many forms
• Usually used in inheritance
• Call a function, which has different implementations
Polymorphism
59

#include <iostream> class Triangle : public Polygon{


using namespace std; public:
void set(){
class Polygon{ cout<<"From Triangle"<< endl;
protected: }
int numVertices; };
float *xCoord, *yCoord;
public: int main(){
void set(){ Polygon *poly;
cout<<"From Polygon"<< endl;
Rectangle rec;
}
Triangle tri;
};
poly = &rec;
class Rectangle : public Polygon{ poly->set();
public: poly = &tri;
void set(){ poly->set();
cout<<"From Rectangle"<< endl; }
}
};
Polymorphism
60

The output of the previous file will be:


From Polygon
From Polygon

By default, C++ checks the type of the variable (poly), call the function in the
corresponding type. This is called static resolution/linage.

If we want C++ to check the contents of the pointer instead of it’s type. We can add
“virtual” to the function in the base class.

class Polygon{
protected:
int numVertices;
float *xCoord, *yCoord;
public:
virtual void set(){
cout<<"From Polygon"<< endl;
}
};
Virtual Function
61

class Polygon{
protected:
int numVertices;
float *xCoord, *yCoord;
set() is a virtual
public:
function
virtual void set(){
cout<<"From Polygon"<< endl;
}
};

When we call a virtual function, such as set(), C++ uses dynamic linkage/late binding.
The selected function is based on the kind of the object.
After adding “virtual” to the previous program, the result will be:
From Rectangle
From Triangle
Pure Virtual Function
62

class Polygon{ class Polygon{


protected: protected:
int numVertices; int numVertices;
float *xCoord, *yCoord; float *xCoord, *yCoord;
public: public:
virtual void set(){ virtual void set()=0;
cout<<"From Polygon"<< endl; };
}
};

set() is a virtual function with set() is a pure virtual function without


implementation. It is polygon’s implementation. Any child/derived class
child/derived class’s option to implement of polygon must implement it.
it’s own version or not.
Interface (Abstract class)
63

Any class with at least one pure virtual function is a abstract class (interface). Abstract
class provides an appropriate base class from which other classes can inherit.
• Abstract class cannot instantiate objects
• If a child class of an abstract class does not implement all pure virtual functions, itself
is an abstract class.
• If a child class of an abstract class does not have any pure virtual function, it is called
concrete class, which can instantiate objects.
Abstract class vs. concrete class
64

class Box{
Abstract class


public:
virtual double getVolume()=0;
protected: Box obj;
double length;
double breadth;
double height;
};

class rectangle : public Box{


Concrete class


public:
double getVolume(){
return length*breadth*height; Rectangle obj;
}
};

class square : public Box{ Abstract class


public:
void info(){}
}; Square obj;
Files and Streams
65

• iostream
• cin: standard input
• cout: standard output

• fstream
• ofstream: represents output file; is used to create files and to write
files
• ifstream: represents input file; is used to read files
• fstream: represents file stream generally; is a superset of ofstream
and ifstream
Open a file
66

• Either ofstream or fstream can do the job


• When open a file, need to specify the mode of the file

Mode Flag Description


ios::app Append mode. Contents will
be appended to the end of the
file
ios::ate File is for output. Read/write
control starts from the end of
the file.
ios::in Open the file for reading
ios::out Open the file for writing
ios::trunc If the file exists, the contents
will be truncated before
opening the file

These values can be combined by logic OR


Open/close a file
67

ofstream object

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

open() function filename Writing mode If file exists, truncate it


“AND”

fstream afile;
afile.open("file.dat", ios::out | ios::in );

outfile.close(); Closes the file


afile.close();
Read/write a stream
68

• Read: Stream extraction operator (>>)


• Write: Stream insertion operator (<<)

eam>
tream> cout << "Enter your age: ";
ace std; cin >> data;
// write inputted data into the file.
outfile << data << endl;

0]; // close the opened file.


outfile.close();
in write mode. }
file;
"afile.dat");

er your name: ";


ata, 100);

tted data into the file.


ata << endl;
Read/write a stream
69
ude <fstream>
ude <iostream>
namespace std;

ain ()

data[100];
en a file in read mode.
eam infile;
e.open("afile.dat");

<< "Reading from the file" << endl;


e >> data;

rite the data at the screen.


<< data << endl;

ad the data from the file and display it.


e >> data;
<< data << endl;

ose the opened file.


e.close();
rn 0;
Dynamic memory
70

Memory of C++ program includes two major parts:


• Stack: All variables declared INSIDE the function will use stack
• Heap: This is unused memory of the program and can be dynamically used when the
program runs.

Many times, we do not know in advance how much memory we need.


• How many Google search requests in the next 10 minutes?
• How many items will be sold on Amazon in next 10 minutes?
• How many phone calls will be made from ATT in the 10 minutes?
• …
Types of memory used by
executable task

data
(static)

heap (dynamic)
Code

Stack
Dynamic memory
72

• new: allocate memory from heap


• delete: de-allocate memory
double* pvalue = NULL; Initialize pointer with NULL
pvalue = new double; Allocate memory

delete pvalue; De-allocate memory
double* pvalue = NULL;
pvalue = new double[6]; Allocate an array

delete [] pvalue; De-allocate memory

double** pvalue = NULL; It is a pointer to pointer


pvalue = new double*[8]; Allocate a two-dimensional array
for(int i=0; i<8; i++)
pvalue[i] = new double[6];

delete [] pvalue; De-allocate memory

You might also like