C++ Classes – Overview and Examples
C. Papachristos
Robotic Workers Lab
University of Nevada, Reno
CS-202
Course , Projects , Labs:
Your 4th Project Deadline still stands for next Wednesday 2/26!
Course Week
CS-202 C. Papachristos
Monday | Tuesday | Wednesday | Thursday | Friday | | Sunday |
|
|
| Lab (8 Sections) |
| | |
| CLASS | PASS Session | CLASS |
| | |
PASS Session | | Project DEADLINE | NEW Project | PASS Session | | PASS Session |
Today’s Topics
CS-202 C. Papachristos
C++ Classes Cheatsheet
Overview and Examples
Classes
CS-202 C. Papachristos
Class Cheatsheet
Declaration:
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Class (Type) Name
Conventions:
Classes
CS-202 C. Papachristos
Class Cheatsheet
Declaration:
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Access Specifiers
Encapsulation - Abstraction:
Classes
CS-202 C. Papachristos
Class Cheatsheet
Declaration:
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Member Variables
inside a single Code Unit.
Encapsulation - Abstraction:
Conventions:
Classes
CS-202 C. Papachristos
Class Cheatsheet
Declaration:
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Member Function / Class Methods
& Operations
inside a single Code Unit.
Encapsulation - Abstraction:
Conventions:
public Class Interface:
private Class Access:
Classes
CS-202 C. Papachristos
Class Cheatsheet
Usual-case Class Interface Design:
class Car {
public:
float addGas(float gallons);
float getMileage();
bool setEngineTiming(double[16]);
private:
char m_licensePlates[9];
float m_gallons;
float m_mileage;
double m_engineTiming[16];
};
Class Interface to Member Data should “go through” Member Functions.
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Implementation:
class Car {
…
bool addGas(float gallons);
float getMileage();
};
float Car::addGas(float gallons){
/* actual code here */
}
float Car::getMileage(){
/* actual code here */
}
Scope Resolution Operator (::)
An Implementation needs to exist for Class Methods
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Instantiation – Default Construction:
<type_name> <variable_name>;
Car myCar;
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Create (Construct) a variable of specific Class type.
Will employ “Default Constructor”
Object
Note: NOT to be confused with Value-Initialization:
Car myCar = Car();
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object Usage:
<variable_name>.<member_name>;
Car myCar;
float mileage = myCar.getMileage(); strcpy(myCar.m_licensePlates,"Gandalf");
Dot Operator – Member-of
(.)
Member Variables & Member Functions
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object Pointers:
<type_name> * <variable_name_Pt>;
Car myCar;
Car * myCar_Pt;
myCar_Pt = &myCar;
(*myCar_Pt).getMileage();
Works the same as any pointer.
Object
Pointer to Object
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object Pointer Usage:
<variable_name_Pt>-><member_name>;
Car myCar;
Car * myCar_Pt = &myCar;
myCar_Pt->getMileage();
strcpy(myCar_Pt->m_licensePlates,"Gandalf");
Arrow Operator – Member-access
(->)
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object Pointer Usage:
<variable_name_Pt>-><member_name>;
Why?
Chaining Operator Precedence ( . , -> )
(*(*(*topClass).subClass).subSubClass).method();
topClass->subClass->subSubClass->method();
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Arrow Operator – Member-access
(->)
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object in Function – By-Value:
Car myCar;
strcpy(myCar.m_licensePlates,"Gandalf");
printCapPlatesMileage(myCar);
cout << myCar.m_licensePlates;
void printCapPlatesMileage(Car car){
char * lP = car.m_licensePlates;
while (*lP = toupper(*lP)){ ++lP; }
cout << car.m_licensePlates << endl;
cout << car.getMileage() << endl;
}
Note:
Will work with Local Object Copy !
Note:
Will modify Object Data !
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object in Function – By-Reference:
Car myCar;
strcpy(myCar.m_licensePlates,"Gandalf");
printModifyCapPlates(myCar);
cout << myCar.m_licensePlates;
void printModifyCapPlates(Car & car){
char * lP = car.m_licensePlates;
while (*lP = toupper(*lP)){ ++lP; }
cout << car.m_licensePlates << endl;
}
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Note:
Not allowed to modify Object Data !
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object in Function – By-const-Reference:
Car myCar;
strcpy(myCar.m_licensePlates,"Gandalf");
printCapPlates(myCar);
cout << myCar.m_licensePlates;
void printCapPlates(const Car & car){
char * lP = (char*)malloc(sizeof(
car.m_licensePlates));
strcpy(lP,car.m_licensePlates);
char * lP_0 = lP;
while (*lP = toupper(*lP)){ ++lP; }
cout << lP_0 << endl;
}
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Note:
Will modify Object Data !
Classes
CS-202 C. Papachristos
Class Cheatsheet
Class Object in Function – By-Address:
Car myCar;
Car * myCar_Pt = &myCar;
strcpy(myCar_Pt->m_licensePlates,"Gandalf");
printModifyCapPlates(myCar_Pt);
cout << myCar.m_licensePlates;
void printModifyCapPlates(Car * car_Pt){
char * lP = car_Pt->m_licensePlates;
while (*lP = toupper(*lP)){ ++lP; }
cout << car_Pt->m_licensePlates
<< endl;
}
class Car {
public:
float addGas(float gallons);
float getMileage();
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Protection Mechanisms – const Method signature:
Car myCar;
cout << myCar.getMileage() << endl;
cout << myCar.addGas(10.0F) << endl;
float Car::getMileage() const {
return m_mileage;
}
float Car::addGas(float gallons) {
if (m_gallons += gallons > MAX_GALLONS)
m_gallons = MAX_GALLONS;
return m_gallons;
}
A “promise” that Method doesn’t modify Object
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Protection Mechanisms – Access Specifiers:
public
Anything that has access to a Car Object (scope-wise) also has access to all public Member Variables and Functions.
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Protection Mechanisms – Access Specifiers:
private
Members (Variables and Functions) that can ONLY be accessed by Member Functions of the Car Class.
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Protection Mechanisms – Access Specifiers:
protected
Members that can be accessed by:
class Hybrid : Car {
…
float gasToElectricRatio();
};
float Hybrid::gasToElectricRatio(){
if (m_gallons < …){ return …; }
}
A Derived Class
Classes
CS-202 C. Papachristos
Class Cheatsheet
Member Functions – Accessors (“Getters”)
Name starts with get, ends with Member name.
Allows retrieval of non-public Data Members.
float Car::getMileage() const {
return m_mileage;
}
Note: Don’t generally take in arguments.
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Member Functions – Mutators (“Setters”)
Name starts with set, ends with Member name.
Controlled changing of non-public Data Members.
bool Car::setEngineTiming(double t_in[16]){
for (int i=0;i<16;++i){
if (t_in[i]<… || t_in[i]>…){ return false; }
}
for (int i=0;i<16;++i){
m_engineTiming[i]=t_in[i];
}
return true;
}
Note: In simple case, don’t return anything (void).
In controlled setting, return success/fail (bool).
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Member Functions – Facilitators (“Helpers”)
Provide support for the Class’s operations.
float Car::addGas(float gallons) {
if (m_gallons += gallons > MAX_GALLONS)
m_gallons = MAX_GALLONS;
return m_gallons;
}
Note:
public if generally called outside Function.
private/protected if only called by Member Functions.
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[16];
};
Classes
Class Cheatsheet
Classes and Code File Structure
#ifndef CAR_H_
#define CAR_H_
#define NUMVALVES 16
class Car {
public:
float addGas(float gallons);
float getMileage() const ;
char m_licensePlates[9];
protected:
float m_gallons, m_mileage;
private:
bool setEngineTiming(double[16]);
double m_engineTiming[NUMVALVES];
};
#endif
#include <iostream>
#include "Car.h"
#define MAX_GALLONS 20.0
float Car::getMileage() const {
return m_mileage;
}
float Car::addGas(float gallons) {
if (m_gallons += gallons > MAX_GALLONS)
m_gallons = MAX_GALLONS;
return m_gallons;
}
bool Car::setEngineTiming(double t_in[16]){
for (int i=0;i<16;++i){
if (t_in[i]<… || t_in[i]>…) return false;
}
for (int i=0;i<16;++i){
m_engineTiming[i]=t_in[i];
}
return true;
}
Class Header File: Car.h
Class Source File: Car.cpp
CS-202 C. Papachristos
Classes
CS-202 C. Papachristos
#include <iostream>
#include <…>
#include "Car.h"
int main(){
Car myCar;
Car * myCar_Pt = &myCar;
strcpy(myCar_Pt->m_licensePlates,"Gandalf");
printCapPlates(myCar_Pt);
cout << myCar.m_licensePlates << endl;
cout << myCar.getMileage() << endl;
cout << myCar.addGas(10.0F) << endl;
return 0;
}
Program File: car_program.cpp
Class Cheatsheet
Classes and Code File Structure
Note: Compile all your source (.cpp) files together with� g++ car_program.cpp Car.cpp
Class Cheatsheet
Constructor(s):
Special Function:
“Constructors have no names and cannot be called directly.”
“They are invoked when instatintation takes place.”
“They are selected according to the rules of initialization.”
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Classes
CS-202 C. Papachristos
Class Cheatsheet
Default (empty) ctor:
Car();
Car::Car(){
strcpy(m_licensePlates, DFT_PLTS);
m_gallons = DFT_GLNS;
m_mileage = 0;
m_engineTiming = _def_DFT_TIM;
}
Note:
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Overloaded (parametrized) ctor:
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car::Car(char licPlts[PLT], float glns,
float mileage, const double engTim[VLV]){
strcpy(m_licensePlates, licPlts);
m_gallons = glns;
m_mileage = mileage;
for (int i=0; i<VLV; ++i)
m_engineTiming[i] = engTim[i];
}
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Overloaded (parametrized) ctor:
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car::Car(char licPlts[PLT], float glns,
float mileage, const double engTim[VLV]){
/* num of args resolves implementation */
}
Note:
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Overloaded (parametrized) ctor:
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car car("Gandalf", 5. ,0. , new double[VLV]
{0.,1.,2.,3.,…,3.,0.,1.,2.});
Car car("Gandalf", 5. ,0.);
Car car("Gandalf", 5.);
Car car("Gandalf");
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
or
or
or
No Parameter skipping !
Classes
CS-202 C. Papachristos
Class Cheatsheet
Overloaded (parametrized) ctor:
Caveat:
Car(char licPlts[PLT], float glns);
Car(char[PLT], float);
Car(char licPlts[PLT], float mlg);
Car(char[PLT], float);
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Copy (class-object) ctor:
Car(const Car &car);
Car::Car(const Car & car){
strcpy(m_licensePlates,car.m_licensePlates);
m_gallons = car.m_gallons;
m_mileage = car.m_mileage;
for (int i=0; i<VLV; ++i)
m_engineTiming[i] = car.m_engineTiming[i];
}
Same Class:
class Car {
public:
Car();
Car(char licPlts[PLT],
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char m_licensePlates[PLT];
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Copy (class-object) ctor:
Class now contains raw Pointer Member (char*):
Car::Car(){
m_licensePlates = (char*)malloc(PLT);
/* rest of Default ctor statements */
}
Car::Car(const char* licPlts, float glns,
float mileage, const double engTim[VLV]){
m_licensePlates = (char*)malloc(PLT);
/* rest of Overloaded ctor statements */
}
class Car {
public:
Car();
Car(const char * licPlts,
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char * m_licensePlates;
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Copy (class-object) ctor:
Shallow-Copy ctor copies raw Pointer, not Data!
Car myCar("Gandalf");
Car myCarCpy(myCar);
class Car {
public:
Car();
Car(const char * licPlts,
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char * m_licensePlates;
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
myCar |
m_licensePlates(*) |
m_gallons, m_mileage |
m_engineTiming[VLV] |
G
a
n
d
a
l
f
0
Values
0.
1.
2.
…
0.
1.
2.
0.
1.
2.
…
0.
1.
2.
myCarCpy |
m_licensePlates(*) |
m_gallons, m_mileage |
m_engineTiming[VLV] |
Pointing-to
Array
(non-Raw)
Classes
CS-202 C. Papachristos
Class Cheatsheet
Copy (class-object) ctor:
Deep-Copy ctor will allocate-&-copy Data!
Function Definition:
Car::Car(const Car &car){
m_licensePlates = (char*)malloc(PLT);
strcpy(m_licensePlates,car.m_licensePlates);
m_gallons = car.m_gallons;
m_mileage = car.m_mileage;
for (int i=0; i<VLV; ++i)
m_engineTiming[i] = car.m_engineTiming[i];
}
class Car {
public:
Car();
Car(const char * licPlts,
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char * m_licensePlates;
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Copy (class-object) ctor:
Car myCar("Gandalf");
Car myCarCpy(myCar);
myCar.m_licensePlates[4] = 0;
cout << myCar.m_licensePlates << ","
<< myCarCpy.m_licensePlates << endl;
Shallow-Copy ctor will only copy raw Pointer:
Explicit Deep-Copy ctor will allocate-copy Data:
Note:
class Car {
public:
Car();
Car(const char * licPlts,
float glns=DFT_GLNS, float mlg=0,
const double engTim[VLV]=DFT_TIM);
Car(const Car &car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char * m_licensePlates;
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Member Initializer List(s) (ctor Definition only):
Car::Car(const char * licPlts, float glns,
float mlg, int fId,
const double engTim[VLV]) :
m_gallons( glns ) , m_mileage( mlg ) ,
m_frameId( fId ) {
// m_frameId = fId; wouldn’t work (const)!
}
Note: With a const Member, needs to exist a
Member Initialization List for every Constructor !
Car myCar("Gandalf",0,0,11000); //11000 years
class Car {
public:
Car();
Car(const char* licPlts,float glns
=DFT_GLNS,float mlg=0,int fId=NO_F
,const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addGas(float gallons);
float getGallons() const ;
float getMileage() const ;
char * m_licensePlates;
protected:
float m_gallons;
float m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
const int m_frameId;
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Member Initializer List(s):
class Driver {
public:
Driver(){}
Driver(char name[PLT], int fId);
private:
char m_name[PLT];
Car m_car;
};
Driver::Driver(const char* name, int fId=NO_F) :
m_name(name) , m_car(name,0,0,fId) {
// Driver & m_car instantiated & initialized
}
class Car {
public:
Car();
Car(char licPlts[PLT],float glns
=DFT_GLNS,float mlg=0,int fId=NO_F
,const double engTim[VLV]=DFT_TIM);
Car(const Car & car);
float addG/M(float gal/mil);
float getG/M() const ;
char m_licensePlates[PLT];
protected:
float m_gallons, m_mileage;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV];
const int m_frameId;
};
Driver ctor Parameter re-used for Car ctor.
ctor-in-ctor Call
Classes
CS-202 C. Papachristos
Class Cheatsheet
Delegating Constructor (C++11):
Car(char lP[PLT], int fId) :
Car(lP, DFT_GLNS,0, fId, DFT_TIM)
{ /* delegating ctor body … */ }
Default Member Initialization (C++11):
class Car {
public:
Car();
Car(char licPlts[PLT],float glns
=DFT_GLNS,float mlg=0,int fId=NO_F
,const double engTim[VLV]=DFT_TIM);
Car(char lP[PLT], int fId) : Car(lP,DFT_GLNS,0,fId,DFT_TIM){ … }
float addG/M(float gal/mil);
float getG/M() const ;
char m_licensePlates[PLT] = "Gdf";
protected:
float m_gallons = DFT_GLNS;
float m_mileage = 0;
private:
bool setEngineTiming(double[VLV]);
double m_engineTiming[VLV] = {…};
const int m_frameId;
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
static Data Members:
Car::Car(){ s_carFactoryCnt++; } //dflt ctor
cout << Car::s_carFactoryCnt; //via class
Car myCar1; //call dflt ctor, increment cnt
cout << myCar1.s_carFactoryCnt; //via object
static Member Function:
Car myCar2; //call dflt ctor, increment cnt
cout << Car::getCarFactoryCnt() << "==" <<
<< myCar1.getCarFactoryCnt() << "==" <<
<< myCar2.getCarFactoryCnt() ; //2==2==2
class Car { //Class Header
public:
Car();
Car(char licPlts[PLT],float glns
=DFT_GLNS,float mlg=0,int fId=NO_F
,const double engTim[VLV]=DFT_TIM);
…
static int getCarFactoryCnt();
private:
// declaration of static member
static int s_carFactoryCnt;
};
#include <Car.h> //Class Source
// definition of static member
int Car::s_carFactoryCnt = 0;
int Car::getCarFactoryCnt(){
return Car::s_carFactoryCnt;
} …
Classes
CS-202 C. Papachristos
Class Cheatsheet
static Local Variables in Class Methods:
float Car::addG(float gallons){
static int refill_cnt = 0;
cout<<"Refilled "<< ++refill_cnt <<" times"<<endl;
m_gallons += gallons;
}
Car myCar1, myCar2;
myCar1.addG(10.0); Output: Refilled 1 times
myCar2.addG(10.0); Output: Refilled 2 times
Notes (Why is it usually such a “bad” design choice):
class Car {
public:
Car();
Car(char licPlts[PLT],float glns
=DFT_GLNS,float mlg=0,int fId=NO_F
,const double engTim[VLV]=DFT_TIM);
Car(const Car &car);
float addG/M(float gallons);
float getG/M() const ;
static int getCarFactoryCnt();
char m_licensePlates[PLT];
protected:
float m_gallons, m_mileage;
private:
bool getEngineTiming(double[VLV]);
double m_engineTiming[VLV];
const int m_frameId;
static int s_carFactoryCnt;
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading – non-Member of Class.
const Money operator–(const Money & mn) �{ return Money(-mn.getD(),-mn.getC()); }
Money myMoney(99,25), notMyMoney = - myMoney;
bool operator==(const Money& mn1, const Money& mn2)
{ return mn1.getD()==mn2.getD() && mn1.getC() == mn2.getC(); }
const Money operator+(const Money& mn1, const Money& mn2)
{ return Money(mn1.getD()+mn2.getD(),mn1.getC()+mn2.getC()); }
Money myMoney(99,25), yourMoney(0,75);
bool ourMoneyEqual = myMoney == yourMoney;
Money ourMoney = myMoney + yourMoney;
return: a const Unnamed Class Object
Note:
Operator(s) should handle Class specifications
(e.g. prevent m_cents rollover)
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars;
int m_cents;
};
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading – Class Member Function.
void Money::operator=(const Money& mn) �{ m_dollars = mn.m_dollars; m_cents = mn.m_cents; }
Money myMoney(99,25), myMoneyAgain = myMoney;
A Class method, like saying: myMoneyAgain.operator=(myMoney);
const Money Money::operator+(const Money& mn) const
{ return Money(m_dollars+mn.m_dollars, m_cents+mn.m_cents); }
Money myMoney(99,25), yourMoney(0,75);
Money ourMoney = myMoney + yourMoney;
Calling Object is like 1st parameter: myMoney.operator+(yourMoney);
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
void Money operator= (const Money & m);
const Money operator+
(const Money & m) const;
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars;
int m_cents;
char * m_owner;
};
Note: If none specified, compiler creates a default Assignment Operator (Member-Copy) for Class Objects. Remember: Shallow-Copy vs Deep-Copy.
Classes
CS-202 C. Papachristos
Class Cheatsheet
const Money operator+(const Money &a,const Money &b)
{ return Money(1); } //non-Member
const Money Money::operator+(const Money &b) const
{ return Money(2); } //Class Member
warning: ISO C++ says that these are ambiguous …
Money m1,m2, m3 = m1 + m2;
Money m4 = m1 .operator+ ( m2 );
const Money operator-(const Money & mn)
{ return Money(-mn.getD(), -mn.getC()); }
const Money operator-(const Money & m) const
{ return Money(m_dollars-mn.m_dollars, m_cents-mn.m_cents); }
Money m5 = - m1 ; //Unary call
Money m6 = m1 – m2 ; //Binary call
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
const Money operator+
(const Money & m) const;
const Money operator-
(const Money & m) const;
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars;
int m_cents;
};
Result: 1
Result: 2
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading
const Money Money::operator+(const Money & mn)const{
return Money(m_dollars + mn.m_dollars,
m_cents + mn.m_cents);
}
Why const-Value ?
Money a(4, 50), b(3, 25), c(2, 10);
(a + b);
c = (a + b);
(a + b) = c;
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
void operator= �(const Money & m);
const Money operator+
(const Money & m) const;
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars;
int m_cents;
};
Evaluates to: Unnamed Object
OK…
No !!!
Prevents (&protects) us from altering the returned value…
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading
const Money& Money::operator+(const Money& mn) const
{ return Money(m_dollars + mn.m_dollars,
m_cents + mn.m_cents); }
warning: returning reference to temporary.
Money a(4, 50), b(3, 25);
const Money* ab_Pt = &(a + b);
cout << ab_Pt->getD()
<<","<< ab_Pt->getC();
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
void Money operator= (const Money & m);
const Money & operator+
(const Money & m) const;
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
};
7
75
No !
This is UNSAFE !
Function return does not guarantee an immediate Stack frame wipe!
Note: Especially if the return type is not a const-Reference ! (…)
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading
Returned: <type_id> & , internal Member Reference.
int & Money::operator[](unsigned int index)
{ return m_transID [ index ]; }
Money hugeCheck(1000000);
int transCnt = 0;
hugeCheck [ transCnt++ ] = BANK_TRANS;
hugeCheck [ transCnt++ ] = BRIBE_TRANS;
hugeCheck [ transCnt++ ] = BANK_TRANS;
if (hugeCheck [ 1 ] == BRIBE_TRANS)
{ cout << "Illegal Activity!"; }
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money &m);
int & operator[](
unsigned int index);
const Money& operator+
(const Money & m) const;
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
int m_transID[T_HIST];
};
Write-to
Read-from
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading w/ Cascading
Returned: <i/o>stream & , Reference to passed 1st Parameter.
ostream & operator<<(ostream & os, const Money & mn){
os << "$" << mn.m_dollars << "." << mn.m_cents;
return os;
}
istream & operator>>(istream & is, Money & mn){
char dollar, point;
is >> dollar >> mn.m_dollars >> point >> mn.m_cents;
return is;
}
Example: Money myMoney;
cin >> myMoney;
w\ Cascading: cout << "I have: " << myMoney << "right now";
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
friend ostream &
operator<<(ostream & os,
const Money & m);
friend istream &
operator>>(istream & is,
Money & m);
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
};
Note: Non-Member friend functions
granted private Data access.
Classes
CS-202 C. Papachristos
Class Cheatsheet
Operator Overloading w/ Cascading
Returned: <class_type> & , Reference to Calling Object.
Money & Money::operator=(const Money & m){
this->m_dollars = m.m_dollars;
this->m_cents = m.m_cents;
this->output();
return *this;
}
Example:
Money moneyPack1,moneyPack2, moneyPack3(49,99);
moneyPack1 = moneyPack2 = moneyPack3;
class Money{
public:
Money();
Money(int dollars,
int cents=0);
Money(const Money & m);
Money & operator=(const
Money & m);
void output();
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
};
Output: $49.99
$49.99
Chaining Assignment Operator by returning Calling Object Reference
this : A pointer to the currently Calling
Object inside a Member Function
Classes
CS-202 C. Papachristos
Class Cheatsheet
Overloading Pre-Increment Operator(s) ( ++ ) , ( -- ):
Money & Money::operator++(){
m_cents++; … //mutates calling object
return *this;
}
Note:
Modifies calling Object and returns a Reference to it.
No Object Copy operation!
Money myMoney(0,99);
Money myMoreMoney = ++ myMoney;
class Money{
public:
Money();
Money(int d, int c=0);
Money(const Money & m);
Money & operator++();
Money & operator--();
Money operator++(int);
Money operator--(int);
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
};
{100,0}
{100,0}
Classes
CS-202 C. Papachristos
Class Cheatsheet
Overloading Post-Increment Operator(s) ( ++ ) , ( -- ):
Money Money::operator++(int dummy){
Money moneyCopy(*this);
this->m_cents++; … //mutates calling object
return moneyCopy;
}
Note: Keeps a Copy of calling Object to return and
then modifies calling Object (same as before).
Money myMoney(0,99);
Money mySameMoney = myMoney ++;
{99,0}
{100,0}
class Money{
public:
Money();
Money(int d, int c=0);
Money(const Money & m);
Money & operator++();
Money & operator--();
Money operator++(int);
Money operator--(int);
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
};
Classes
CS-202 C. Papachristos
class Money{
public:
Money();
Money(int d, int c=0);
Money(const Money & m);
Money & operator=(const
Money & rhs);
bool isThis(const
Money & m);
void setD/C(int dc);
int getD/C() const;
private:
int m_dollars, m_cents;
};
Keyword this
Checking if the Calling Object is exactly the same as the Object passed as argument!
bool Money::isThis(const Money & m){
if (this == &m)
return true;
else
return false;
}
Money & Money::operator=(const Money & m){
if (this != &m){ //check if trying to assign from self
//perform assignment from m to calling object
//only if other object m is a separate object
}
return *this; //return calling object by-Reference
}
Classes
CS-202 C. Papachristos
Examples
On the Whiteboard !
Pointers / Arrays as function params – sizeof(…) results ?
Pointers to Functions !
const-ness, when and where can it be cast’ed away ?
Constructors, Destructors, Arrays of Objects .
Implementation of Classes & their Methods – this – C/static function vs Method !
Factory pattern (simple for now – no pointers) …
Time for Questions !
CS-202
CS-202 C. Papachristos