C++ Recitation
C++ Recitation
Programming
by Merve Asiler
Class & Object
• Class: A data structure that keeps variables and methods inside.
• Object: An instance of a class.
You can consider int, float, double, char, string, etc. as the built-in
data types whereas classes are the data types made by you.
int a;
ClassName b;
Sample Class Structure
class ClassName { class Circle {
int main() {
class Circle {
Circle c;
private:
c.setRadius(100);
int radius;
Circle* d = new Circle();
float center[3];
d->setRadius(150);
public:
delete d;
void setRadius(float r);
return 0;
};
}
Constructors/Destructors
Constructors Destructors
public:
Polynomial() { // constructor
degree = 0;
coeffs = new double[1];
coeffs[0] = 0;
}
~Polynomial() { // destructor
delete[] coeffs;
}
};
Constructor Properties
➢Constructors are functions that get called when a class is instantiated.
➢Constructors have the same name as their class.
➢Constructors may not pass off control to another constructor.
➢A default (zero argument) constructor is provided when no other
constructors declared.
Constructor Properties (cont’d)
➢A constructor can be overloaded which means there can be more
than one constructor of a class.
➢If overloaded, each constructor should have a distinct parameter list
to uniquely determine the which constructor is called when an object
is being instantiated.
➢The compiler assumes a default constructor unless you define one.
The default constructor does not take any parameters (it is a nullary
constructor).
Destructor Properties
➢Destructors are methods that get called automatically when a class
instance is destroyed.
(i) If the object is not dynamically allocated (i.e. if held in stack),
then destructor is called when the local scope of its existence has
finished (e.g. At the end of a function).
(ii) If the object is dynamically allocated, then destructor is called
when delete operator is called.
➢Destructors have no return type and have the same name as their
class with a “~” prepended.
Destructor Properties (cont’d)
➢If no destructor is defined, a default destructor, which calls the
destructor for all elements is provided by compiler. Note that default
constructor does not deallocate the dynamically allocated members.
➢You may need to use destructor when
(i) the object assigns dynamic memory during its lifetime. In this
case, allocated memory should be released to avoid memory leaks
(ii) the object opens resources such as files. Resources should be
properly released, otherwise data loss may occur.
Constructors/Destructors
Class A {
int var1;
float var2;
public:
A() {};
A(int v1, float v2) : var1(v1), var2(v2) {};
}
Class B {
A var1;
A* var2;
public:
B() {var2 = new A(0, 1.0);}
~B() {delete var2;}
}
Copy Constructor
• You can also construct an object by copying from another object of
the same type. In this case copy constructor is called automatically.
int main(void) {
vector<double> c; c.push_back(1.1); c.push_back(2.0);
Polynomial r(c);
Polynomial s(r); // Construct s from r
Polynomial p;
p = s; // Assign s to p
Polynomial q = p; // Construct q from p
...
f(s); // s is passed by value,
// it’s copied with the copy constructor
g(p); // p is passed by reference
}
‘Static’ Keyword
• Static members are not specific to object, but valid for whole class.
That is a common variable for all instances of that class.
What would
happen if
mother had
only one of
those
constructors?
Inheritance
Inheritance type:
The inherited members will have access permission of at least the
specified modifier given in the declaration:
derived_constructor_name (parameters) :
public/protected/private base_constructor_name
(parameters) {…}
Multiple Inheritance
A class can be derived and carry properties form multiple classes just
by separating the base classes with comma in the declaration.
Polymorphism
• C++ polymorphism means that a call to a member function will cause
a different function to be executed depending on the type of object
that invokes the function.
class Virus {…};
class A : public Virus {…};
Virus* v;
A a;
v = &a; /* referencing object of type A with
pointer of type Virus.
Thanks to polymorphism ☺ */
Virtual Functions
Virtual member functions
▪ Accessed by indirection through pointer in object.
▪ May be redefined in derived subclasses.
▪ The exact function to call determined dynamically
▪ Non-virtual functions are ordinary functions.
▪ Cannot redefine in subclasses (but can overload).
▪ Member functions are virtual if explicitly declared or inherited as
virtual, else non-virtual
Virtual Functions
class parent {
int main() {
public:
parent p; child c; parent *q;
void printclass() {
p.printclass();
printf("p ");
p.printvirtual();
};
virtual void printvirtual() {
c.printclass();
printf("p ");
c.printvirtual();
};
c.printOwnFunction();
};
class child : public parent {
q = &p;
public:
q->printclass();
void printclass() {
q->printvirtual();
printf("c ");
};
q = &c;
void printOwnFunction() {
q->printclass();
printf("c ");
q->printvirtual();
};
dynamic_cast<child*>(q)->printOwnFunction();
virtual void printvirtual() {
printf("c ");
return 0;
};
} // output: p p c c c p p p c c
};
Abstraction
• Abstract class is a class which you cannot instantiate.
• An abstract class is a class that is designed to be specifically used as a
base class.
• An abstract class contains at least one abstract method which is a
pure virtual function.
• You declare a pure virtual function by using a pure specifier (= 0) in
the declaration of a virtual member function in the class declaration.
• These methods forces derived classes to implement those methods.
Abstraction
class Virus {
class A : public Virus {
protected:
public:
int rna_length;
A(int length, string rna) :
string RNA;
Virus(length, rna) {};
public:
Virus(int length, string rna) {
void mutate() {…}
rna_length = length;
};
RNA = rna;
}
class B : public Virus {
public:
void printRNA() const {
A(int length, string rna) :
cout << RNA << endl;
Virus(length, rna) {};
} abstraction
void mutate() {…}
virtual void mutate() = 0;
};
};
Templates
• Templates are a feature of the C++ programming language that allow
functions and classes to operate with generic types.
• It allows a function or class to work on many different data types
without being rewritten for each one.
Templates
Output:
8
J
‘friend’ Keyword
• If a class A is introduced to another class B as ‘friend’, then B gives
permission to A for accessing any private/protected members.
• Instead of a class, only a single function can be introduced as friend
also.
Syntax: class A { class B {
B* b; friend class A;
public: int num;
void increaseNum() { public:
b->num ++; friend void func(B b);
}; };
}; void func(B b) {
cout << b.num << endl;
}
Composition
➢ Relationship between objects, where one object owns or has the other object.
➢ For the example below, Car has or owns Motor.
▪ When Car is build, it’s motor is built also.
▪ When Car is destroyed it’s motor is destroyed.
class Car {
private:
Motor* motor;
public:
Car() {motor = new Motor();}
~Car() { delete motor; }
};
Aggregation
➢ In composition, when the owning object is destroyed, so are the contained objects.
➢ In aggregation this is not necessarily true.
➢ Aggregation is a form of composition, where contained objects can still “live” after the owning object is
released.
➢ For the example below, Departments has professors, if department is closed, professors still live...
class Department {
private:
Professor* professor;
public:
Department(Professor* prof):professor(prof) { }
~Department() { }
};
‘typedef’ Keyword
Typedef is used to create an alias to a type
#ifndef FILENAME_H
#define FILENAME_H
<header file body here>
#endif /* FILENAME_H */
CFLAGS= -c –Wall
all: exe_prog