Classes and Objects

Classes and Objects

Contents

Members of the class. Access levels, Encapsulation

Class: (interface)Prototype and implement

Contructors and destructors

const member function

Constructor initializer

Copy constructor

Object's lifecycle

Classes and Objects

Class = Type (Data + Operations)

Members of the class

Data

data members (properties)

Operations

methods (behaviors)

Each members is associated with an access level:

private -

public +

protected #

Classes and Objects

Object = Instance of a class

An employee object: Employee emp;

  • Properties are the characteristics that describe an object.
    • What makes this object different?
      • id, frirstName, lastName, salary, hired
  • Behaviors answer the question
    • What can we do to this object?
      • hire(), fire(), display(), get and set data members
Classes and Objects

Encapsulation

An object encapsulates data and functionality

Employee
- id: int
- firstName: string
- lastname: string
- salary: int
- hired: bool
+ Employee()
+ display(): void{query}
+ hire(): void
+ fire(): void
+ setFirstName(string): void
+ setLastName(string): void
+ setId(int): void
+ setSalary(int): void
+ getFirstName(): string{query}
+ getLastName(): string{query}
+ getSalary(): int{query}
+ isHired(): bool{query}
+ getId(): int{query}
Classes and Objects

Class creation

class declaration - prototype(interface)

Employee.h

class definition - implementation

Employee.cpp

Classes and Objects

Declaration Employee

class Employee{
public:
	Employee();
	void distplay() const;
	void hire();
	void fire();
	//getters and setters
	void setFirstName(string firstName);
	void setLastName(string lastName);
	void setId(int id);
	void setSalary(int salary);
	string getFirstName() const;
	string getLastName() const;
	int getId() const ;
	int getSalary() const;
	bool isHired() const ;
private:
	int id, salary;
	string firstName, lastName;
	bool hired;
}
				
Classes and Objects

The Constructor and the object's state

The state of an object is defined by its data members

The constructor is responsiable for the initial state of the object

Enployee::Employee():
	id(-1),
	firstName(""), 
	lastName(""), 
	salary(0), 
	hired(false){
	
}
Members are initialized through the constructor initializer list
Employee::Employee(){
	m = -1;
	firstName = "";
	lastName = "";
	salary = 0;
	hired = false;
}

Members are assigned

Only constructors can use this initializer-list systax!!!

Classes and Objects

Constructors

Responsibility: data members initialization of a class object

Invoked automatically for each object

Have the same name as the class

Have no return

A class can have multiple constructors(function overloading)

May not be declared as const

constructors can write to const objects

Classes and Objects

Member initialization (C++11)

class C{
	string s = "abc";
	double d = 0;
	char* p = NULL;
	int y[5] = {1, 2, 3, 4, 5};
public:
	C();
}
				
class C{
	string s;
	double d;
	char* p;
	int y[5];
public:
	C(): s("abc"),
		d(0.0),
		p(NULL),
		y{1, 2, 3, 4, 5}{

	}
}
				
Classes and Objects

Defining a member function

Employee.cpp

A const member function cannot the object's state, can be invoked on const objects

void Employee::hire(){
	hired = true;
}
string Employee::getFirstName() const{
	return firstName;
}
			
Classes and Objects

Defining a member function

void Employee::display() const{
	cout << "Employee: " << lastName << ", " << firstName << endl;
	cout << (hired ? "Current Employee" : "Former Employee") << endl;
	cout << "Employee Id: " << id << endl;
	cout << "Salary: " << salary << endl;
}
			
Classes and Objects

Using const Member functions

void foo(const Employee& e){
	e.display();//OK. display() is a constant member function
	e.fire();//ERROR. fire() is not a constant member function
}
void main(){
	Employee emp;
	emp.setFirstName("Robert");
	emp.setLastName("Black");
	emp.setId(1);
	emp.setSalary(10000);
	emp.hire();
	emp.display();
	foo(emp);
}
			
Classes and Objects

Class Employee

#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namesapce std;
class Employee{
public:
	Employee();
protected:
	int id;
	string firstName;
	string lastName;
	int salary;
	bool hired
}
#endif
				
#include "Employee.h"
Employee::Employee():
	id(-1),
	firstName(""),
	lastName(""),
	salary(0),
	hired(false){

}
string Employee::getFirstName() const{
	return firstName;
}
				
Classes and Objects

Object life cycles

Creation

Assignment

Destruction

Classes and Objects

Object creation

void main(){
	Employee emp;
	emp.display();
	Employee *pe = new Employee();
	pe->display();
	delete pe;
}
			

When an object created

One of its constructors is executed

All its embedded objects are also created

Classes and Objects

Object creation - constructors

Default constructor (0-argument constructor)

Employee::Employee():id(-1), firstName(""), lastName(""), salary(0), hired(false){
}
Employee::Employee(){
}

When you need

Employee employees[10];
			

Memory allocation

constructor call on each allocated object

Classes and Objects

Object creation - constructors

Compiler-generated default constructor

class Value{
public:
	void setValue(double val);
	double getValue() const;
private:
	double val;
}
			

If a class does not specify any constructors, the compiler will generate one that does not take any arguments

Classes and Objects

Constructors: default and delete specifiers(C++ 11)

class X{
	int i = 4;
public:
	X(int a):i(a){}
	X() = default;
};
			

Explicitly forcing the automatic generation of a default constructor by the complier.

Classes and Objects

Constructors: default and delete specifiers(C++ 11)

class X{
	int a;
public:
	X(double a){
		this -> a = a;
	}
};
X x2(3.14); //Good
X x1(10); //Good (int -> double conversion)
				
class X{
	int a;
public:
	X(int) = delete;
	X(double a){
		this -> a = a;
	}
};
X x1(10); //ERROR
X x2(3.14); //Good
				
Classes and Objects

Constructor initializer

class ConstRef{
public:
	ConstRef(int&);
private:
	int i;
	const int ci;
	int& ri;
};
ConstRef::ConstRef(int &a){
	i = a;
	ci = a;//ERROR: cannot assign to a const
	ri = a;//ERROR: uninitialized reference member
}
			
ConstRef::ConstRef(int *a):i(a), ci(a), ri(a){
}
Classes and Objects

Constructor initializer

Data types that must be initialized in a constructor-initializer

const data member

Reference data members

Object data members having no default constructor

Supperclasses without default constructor

Classes and Objects

A non-default Constructor

Employee::Employee(int id, string firstName, string lastName, int salary, bool hired):
	id(id),
	firstName(firstName),
	lastName(lastName),
	salary(salary),
	hired(hired)
{
}
			
Classes and Objects

Delegating Constructor(C++ 11)

class SomeType{
	int number;
public:
	SomeType(int num):number(num){
	}
	SomeType():SomeType(0){
	}
};
			
Classes and Objects

Copy Constructor

Employee emp(1, "Robert", "Black", 4000, true);
			

Called in one of the following cases

Employee emp2(emp); //copy-constructor called
Employee emp3 = emp; //copy-constructor called
void foo(Employee emp);//copy-constructor called
			

If you don't define a copy-constructor explicitly, the compiler creates one for you

This performs a bitswise copy - shallow copy

Classes and Objects

Class Stack

//Stack.h
#ifndef STACK_H
#define STACK_h
class Stack{
public:
	Stack(int capacity);
	void push(double val);
	double top() const;
	bool isFull() const;
	bool isEmpty() const;
private:
	int capacity;
	double *elements;
	double *top;
}
#endif
				
//Stack.cpp
#include "Stack.h"
Stack::Stack(int capacity){
	this.capacity = capacity;
	elements = new double[capacity];
	top = elements;
}
void Stack::push(double val){
	if(!isFull()){
		*top = val;
		top++;
	}
}
				
Classes and Objects

Test Stack

#include "Stack.h"
void main(){
	Stack s1(3);
	Stack s2 = s1;
	s1.push(1);
	s2.push(2);
	cout << "s1: " << s1.top() << endl;
	cout << "s2: " << s2.top() << endl;
}
			
Classes and Objects

Copy constructor: T(const T&)

//Stack.h
#ifndef STACK_H
#define STACK_H
class Stack{
public:
	//Copy constructor
	Stack(const Stack&);
private:
	int capacity;
	double* elements;
	double* top;
}
#endif
				
//Stack.cpp
#include "Stack.h"
Stack::Stack(const Stack& s){
	capacity = s.capacity;
	elements = new double[capacity];
	int n = s.top - s.elements;
	for(int i = 0; i < n; i++){
		elements[i] = s.elements[i];
	}
	top = elements + nr;
}
				
Classes and Objects

Test Stack

#include "Stack.h"
void main(){
	Stack s1(3);
	Stack s2 = s1;
	s1.push(1);
	s2.push(2);
	cout << "s1: " << s1.top() << endl;
	cout << "s2: " << s2.top() << endl;
}
			
Classes and Objects

Destructor

When an object is destroyed

The object's destructor is automatically invoked

The memory used by the object is freed

Each class has one destructor

Usualy place to perform cleanup work for the object

If you don't declare a destructor → the compiler will generate one, which destroys the object's member

Classes and Objects

Destructor

Syntax: T::~T();

Stack::~Stack(){
	if(element != NULL){
		delete []elements;
		elements = NULL;
	}
}
{
	Stack s(10);//s : constructor
	Stack* s1 = new Stack(5); //s1: constructor
	s.push(3);
	s1->push(10);
	delete s1; //s1: destructor
	s.push(16);
	//Block end //s: destructor
}
Classes and Objects

Default parameters

If the user specifies the arguments → the default are ignored

If the user omits the arguments → the defaults are used

The default parameters are specified only in the method declaration (not in the definition)

//Stack.h
class Stack{
public:
	Stack(int capacity = 5);
	.....	
};
//Stack.cpp
Stack::Stack(int capacity){
	this.capacity = capacity;
	elements = new double[capacity];
	top = element;
}
				
//TestStack.cpp
Stack s1(3); //capacity = 5
Stack s2; //capacity = 5
Stack s3(10); //capacity = 10
				
Classes and Objects

This pointer

Every mothod call passes a pointer to the object for which it called as hidden parameter having the name this

Usage

for disambiguation

Stack::Stack(int capacity){
	this->capacity = capacity;
}