Lect 9-10

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Menoufia University

Faculty of Electronic Engineering

CSE 121: Computer Programming

Dr. Ahmed Hamdy Ahmed Arafa


Computer Science & Engineering Dept
Email: ahmed.arafa@el-eng.menofia.edu.eg
Mobile: +201020069729
Office: CSE Building 4th floor, Room 413
Course Objectives

✓ Overview of basic concepts of C++


✓ Functions in C++
✓ Macros in C++
✓ Arrays and Strings in C++
✓ Overview of basic concepts of object oriented programming in C++
✓ Classes and Objects in C++
✓ Inheritance in C++
Programming Paradigms
✓ The style in which a given program or programming language can be organized.
✓ Approach to solve problem using some programming language.
✓ The paradigm consists of certain structures, features, and opinions about how common programming problems should be solved.
✓ It is used to classify programming languages based on their features.

Paradigms

Imperative Declarative

Object Parallel
Structured Logic Functional Database
Oriented Processing
Imperative Paradigm VS Declarative Paradigm
▪ Imperative (How to do)
✓ Focuses on how the problem should be solved by describing solving steps , step by step which requires understanding of
the functions necessary to solve the problem.
✓ It's called imperative because the programmer instructs exactly what the computer has to do, in a very specific way.
✓ It features close relation to machine architecture
✓ The paradigm consist of several statements and after execution of all the result is stored.
✓ Imperative programming consists of sets of detailed instructions that are given to the computer to execute in a given order.
✓ Structured and object-oriented programming (OOP) languages fall under imperative programming, such as C, C++, C#,
and Java.

▪ Declarative (What to do)


✓ Focuses on what needs to be done rather how it should be done.
✓ Hides away the complexity and makes programming languages closer to human language and thinking.
✓ The programmer declares properties of the desired result, but not how to compute it (no control flow).
✓ Functional , Logic and Database languages such as (SQL , HTML, CSS) are examples of declarative paradigm languages.
Structured Programming
✓ Programming paradigm that uses structured control flow (without goto statement) to improve code clarity and quality.
✓ It has three ways of combining programs (sequencing, selection, and iteration).
✓ The structured program consists of well structured and separated modules.
✓ The program uses single-entry and single-exit elements.

Advantages
• The code is well written and organized.
• Easier to maintain and debug.
• We can execute a block of code repeatedly till the given conditions match.
• Improved decision making power by using some conditions that can decide to execute or not any block of code.
• The structured flow of execution using if/else and for/while.
• Mainly problem based instead of being machine based.
• Development is easier and requires less effort and time.

Disadvantages
• The program depends upon changeable factors like data-types, therefore it needs to be updated with the need on the go.
• Usually the development in this approach takes longer time as it is language-dependent.
Object Oriented Programming (OOP)
✓ OOP mainly focuses on objects that are required to be manipulated.
✓ OOP combines both data and functions into a single unit called object.
✓ The object is a real-world entity that has data (properties/variables) and behavior (methods / Functions).
✓ The basic unit in OOP is the class which is the template / blueprint for creating objects which are instances created from the class.
Advantages of OOP
✓ Data security though data hiding
✓ Encapsulation
✓ Abstraction
✓ Productivity through many libraries that new programs requires.
✓ Inheritance
✓ Code reusability
✓ Flexibility through polymorphism.

Types of Object Oriented Programming


▪ Class-based
✓ Classes are defined and objects are instantiated based on these classes
✓ PHP, C++, Java, C# languages are examples.
▪ Prototype-based
✓ No classes exist
✓ Objects are the primary entities
✓ Objects can be created based on already existing objects chosen as their prototype
✓ Java Script is an example.
Classes in C++.
✓ Building block of programs in Class-based Object-Oriented programming.
✓ It is a user-defined data type, which holds its own data members and member functions.
✓ Classes are created before the main function using the following syntax

Data Members
✓ Attributes /features/variables used to store the data in the memory.
✓ Optional in the class.
✓ Data members Initialization
▪ Directly with declaration in the class
▪ Directly with assignment using object in the main function
▪ Creating specific method for initializing the variables
▪ Using Constructors
Access Modifiers / Specifiers
✓ It means how class members (attributes / methods) can be accessed
▪ Public: members are accessible from outside the class
▪ Private: members cannot be accessed (or viewed) outside the class
▪ Protected: members can be accessed in inherited classes
▪ By default all members are private if no specifier is determined
class ABC {
int x; // Private attribute
int y; // Private attribute
};
Class Methods / Functions in C++.
▪ Member functions in the class are used to process and manipulate the data members.
▪ It represents the behavior of the object.
▪ It is as normal functions in C++ ( Declaration outside the main , Definition outside the main , Call inside the main program).
▪ It can be void or has a return type
▪ It is called inside another function in the same class or other classes (Considering access modifiers) or inside the main program
▪ Declaration and definition of class methods
✓ Combine Definition and Declaration inside the class
class MyClass
{
public:
void myMethod()
{ // Method defined inside the class
cout << "Hello World!";
}
};
✓ Declaration inside the class and Definition Outside the class
class MyClass
{
public:
void myMethod(); // Method/function declaration
};
void MyClass::myMethod() // Method definition outside the class
{
cout << "Hello World!";
}
Objects in C++.
✓ Objects are instances from the class.
✓ Used to access both data members and methods.
✓ Objects are declared inside the main program → ClassName ObjectName;
✓ Member Access operator dot (.) is used to access a member in the object (Function/Attribute)

int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method using the object
myObj.attribute1 = "ABC"; // Access the attribute using the object
return 0;
}
Example 1: Initializing the attributes in the class
Create A class named Car that has three attributes which are the car brand , model and year of production. Create two objects of two different cars
and print them on the screen.
#include<iostream>
using namespace std;
class Car
{
public:
string brand="BMW";
string model=“X5";
int year=1999;
};
int main() {
Car carObj1 ;
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
cout <<"The First Car is:"<<carObj1.brand<<" "<< carObj1.model<<" "<<carObj1.year<< "\n";
cout <<"The Second Car is:"<<carObj2.brand<<" "<< carObj2.model<<" "<<carObj2.year<< "\n";
return 0;
}
Example 2: Initializing attributes in the main function
Create A class named Car that has three attributes which are the car brand , model and year of production. Create two objects of two different cars
and print them on the screen.

#include<iostream> int main() {


// Create The First Car object
using namespace std;
Car carObj1;
class Car carObj1.brand = "BMW";
{ carObj1.model = "X5";
public: carObj1.year = 1999;
string brand;
string model; // Create The Second Car object
Car carObj2;
int year;
carObj2.brand = "Ford";
}; carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout <<"The First Car is:"<<carObj1.brand<<" "<< carObj1.model<<" "<<carObj1.year<< "\n";
cout <<"The Second Car is:"<<carObj2.brand<<" "<< carObj2.model<<" "<<carObj2.year<< "\n";
return 0;
}
Example 3: Initializing its attributes in the main function
Create a student class that have 5 data members for the student which are id, name and three degrees and then create two methods in the class finding
the average degrees and deciding the student grade. Create and object in the main program. All class attributes are initialized directly with declaration.

#include <iostream>
using namespace std;
class Student{
public:
int id;
string name;
float D1;
float D2;
float D3;
public:
float get_degree() {return ((D1+D2+D3)/3 );}
string get_grade( float degree)
{
if (degree<50) return "Fail";
else if(degree>=50 && degree<65) return "Pass";
else if(degree>=65 && degree<75) return "Good";
else if(degree>=75 && degree<85) return "Very Good";
else return "Excellent";
}
};
Example 3: Initializing its attributes in the main function (cont.).
int main()
{
int sid;
string sname;
float sd1,sd2,sd3;
cout<<"Please Enter the Student ID:"<<endl;
cin>>sid;
cin.ignore();
cout<<"Please Enter the Student Name:"<<endl;
getline(cin,sname);
cout<<"Please Enter the Student First Degree:"<<endl;
cin>>sd1;
cout<<"Please Enter the Student Second Degree:"<<endl;
cin>>sd2;
cout<<"Please Enter the Student Third Degree:"<<endl;
cin>>sd3;
Student s1;
s1.id=sid;
s1.name=sname;
s1.D1=sd1;
s1.D2=sd2;
s1.D3=sd3;
cout<<"The Student Information is:\t id \tname \tD2 \tD2 \tD3"<<endl;
cout<<"The Student Information is:\t "<<s1.id<<"\t"<<s1.name<<"\t"<<s1.D1<<"\t"<<s1.D2<<"\t"<<s1.D3<<endl;
cout<<"\nThe Average Degree is:"<<s1.get_degree()<<endl;
cout<<"\nThe Student Grade is:"<<s1.get_grade(s1.get_degree())<<endl;
return 0;
}
Example 4: Initializing the attributes using a method
Create a student class that have 5 data members for the student which are id, name and three degrees and then create three methods in the class for
initializing the class attributes, finding the average degrees and deciding the student grade. Create and object in the main program.

#include <iostream> string get_grade(float degree)


using namespace std; {
if (degree<50) return "Fail";
class Student {
else if(degree>=50 && degree<65) return "Pass";
public:
int id;
else if(degree>=65 && degree<75) return "Good";
string name; else if(degree>=75 && degree<85) return "Very Good";
float D1; else return "Excellent";
float D2; }
float D3; };
public:
void set_members(int a,string b,float d1,float d2,float d3)
{
id=a;
name=b;
D1=d1;
D2=d2;
D3=d3;
}
float get_degree()
{
return ((D1+D2+D3)/3);
}
Example 4: Initializing the attributes using a method (cont.)
int main() {
int x1;
string x2;
float x3,x4,x5;
cout<<"Please Enter the Student ID:"<<endl;
cin>>x1;
cin.ignore();
cout<<"Please Enter the Student Name:"<<endl;
getline(cin,x2);
cout<<"Please Enter the Student First Degree:"<<endl;
cin>>x3;
cout<<"Please Enter the Student Second Degree:"<<endl;
cin>>x4;
cout<<"Please Enter the Student Third Degree:"<<endl;
cin>>x5;
Student s1;
s1.set_members(x1,x2,x3,x4,x5);
cout<<"The Student Information is:\t id \tname \tD2 \tD2 \tD3"<<endl;
cout<<"The Student Information is:\t "<<s1.id<<"\t"<<s1.name<<"\t"<<s1.D1<<"\t"<<s1.D2<<"\t"<<s1.D3<<endl;
cout<<"\nThe Average Degree is:"<<s1.get_degree()<<endl;
cout<<"\nThe Student Grade is:"<<s1.get_grade(s1.get_degree())<<endl;
return 0;
}
Constructors in C++.
✓ What would happen in the previous example if we called the member function get_degree() before having called set_members? An
undetermined result, since the members width and height had never been assigned a value.
Constructor
✓ Special function called constructor, which is automatically called whenever a new object of this class is created, allowing the class
to initialize member variables or allocate storage.
✓ Constructor is function is declared just like a regular member function, but with a name that matches the class name
✓ Constructor never return values (without any return type, not even void) , they simply initialize the object.
✓ Constructor cannot be called explicitly as the regular member functions.
✓ Constructors allocate resources for use during the construction of an object.
✓ Constructors are only executed once, when a new object of that class is created.
✓ Constructors can be overloaded as all functions.
✓ this-> operator can be used to refer to the class members during passing parameters with the same names as the class attributes

Default Constructor (Zero Argument Constructor)


✓ A constructor without or has zero parameter list any arguments or with the default value for every argument
✓ It is used to create objects, which do not have any specific initial value.
✓ If default constructor is not defined by the programmer, then the compiler define it implicitly during compilation.
✓ If the default constructor is defined explicitly by the programmer, then the compiler will not define it implicitly, but it calls the
constructor implicitly.
Example 5: Initializing the attributes using constructor
Create a student class that have 5 data members for the student which are id, name and three degrees and then create three methods in the class for
initializing the class attributes, finding the average degrees and deciding the student grade. Create and object in the main program.
#include <iostream> string get_grade(float degree)
using namespace std; {
class Student { if (degree<50) return "Fail";
public: else if(degree>=50 && degree<65) return "Pass";
int id; else if(degree>=65 && degree<75) return "Good";
string name; else if(degree>=75 && degree<85) return "Very Good";
float D1; else return "Excellent";
float D2; }
float D3; };
public:
Student(int a,string b,float d1,float d2,float d3) Student(int id,string name,float D1,float D2,float D3)
{ {
id=a; this->id=id;
name=b; this-> name=name;
D1=d1; this-> D1=D1;
D2=d2; this-> D2=D2;
D3=d3; this-> D3=D3;
} }
float get_degree()
{
return ((D1+D2+D3)/3);
}
Example 5: Initializing the attributes using constructors(cont.)
int main() {
int x1;
string x2;
float x3,x4,x5;
cout<<"Please Enter the Student ID:"<<endl;
cin>>x1;
cin.ignore();
cout<<"Please Enter the Student Name:"<<endl;
getline(cin,x2);
cout<<"Please Enter the Student First Degree:"<<endl;
cin>>x3;
cout<<"Please Enter the Student Second Degree:"<<endl;
cin>>x4;
cout<<"Please Enter the Student Third Degree:"<<endl;
cin>>x5;
Student s1(x1,x2,x3,x4,x5);
cout<<"The Student Information is:\t id \tname \tD2 \tD2 \tD3"<<endl;
cout<<"The Student Information is:\t "<<s1.id<<"\t"<<s1.name<<"\t"<<s1.D1<<"\t"<<s1.D2<<"\t"<<s1.D3<<endl;
cout<<"\nThe Average Degree is:"<<s1.get_degree()<<endl;
cout<<"\nThe Student Grade is:"<<s1.get_grade(s1.get_degree())<<endl;
return 0;
}
Destructors in C++.
✓ Member Function that is used to destroy the object that has been created by a constructor.
✓ It is invoked automatically whenever an object is going to be destroyed.
✓ Destructor release memory space occupied by the objects created by constructor before destroying the object.
✓ It is the last function that is going to be called before an object is destroyed.
✓ Destructor has the same name as their class name preceded by a tilde (~) symbol.
✓ It is not possible to define more than one destructor (Can’t be overloaded).
✓ Destructor neither requires any argument nor returns any value not even void.
✓ A destructor should be declared in the public section of the class.
✓ The programmer cannot access the address of destructor.
Example 6: Destructors
Create a student class that have 5 data members for the student which are id, name and three degrees and then create three methods in the class for
initializing the class attributes, finding the average degrees and deciding the student grade. Create and object in the main program and remove it after
execution.
#include <iostream> float get_degree()
using namespace std; {
class Student { return ((D1+D2+D3)/3);
public: }
int id; string get_grade(float degree)
string name; {
float D1; if (degree<50) return "Fail";
float D2; else if(degree>=50 && degree<65) return "Pass";
float D3; else if(degree>=65 && degree<75) return "Good";
public: else if(degree>=75 && degree<85) return "Very Good";
Student(int a,string b,float d1,float d2,float d3) else return "Excellent";
{ }
id=a; };
name=b;
D1=d1;
D2=d2;
D3=d3;
}
~Student()
{
cout<<"\n Destructor executed";
}
Example 6: Destructors (cont.)
int main()
{
int x1;
string x2;
float x3,x4,x5;
cout<<"Please Enter the Student ID:"<<endl;
cin>>x1;
cin.ignore();
cout<<"Please Enter the Student Name:"<<endl;
getline(cin,x2);
cout<<"Please Enter the Student First Degree:"<<endl;
cin>>x3;
cout<<"Please Enter the Student Second Degree:"<<endl;
cin>>x4;
cout<<"Please Enter the Student Third Degree:"<<endl;
cin>>x5;
Student s1(x1,x2,x3,x4,x5);
cout<<"The Student Information is:\t id \tname \tD2 \tD2 \tD3"<<endl;
cout<<"The Student Information is:\t "<<s1.id<<"\t"<<s1.name<<"\t"<<s1.D1<<"\t"<<s1.D2<<"\t"<<s1.D3<<endl;
cout<<"\nThe Average Degree is:"<<s1.get_degree()<<endl;
cout<<"\nThe Student Grade is:"<<s1.get_grade(s1.get_degree())<<endl;
return 0;
}
Inheritance in C++.
Inheritance
✓ Inheritance is one of the most important features of Object-Oriented Programming.
✓ It is the capability of a class to derive properties and characteristics from another class.
✓ It is a feature or a process in which, new classes are created from the existing classes.
✓ Inheritance provides an opportunity to reuse the code functionality and fast implementation time.
When we Use inheritance
✓ Assume we want to create a group of classes for some vehicles (Bus, Car, and Truck).
✓ Each vehicle has the methods fuelAmount(), capacity(), applyBrakes().
✓ If we create these classes without inheritance then we will write these methods in each class resulting in duplication of the same code 3
times.

✓ To avoid this type of this duplication and make the methods code reusable , inheritance is used.
✓ We can easily create a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class.
Inheritance in C++ (cont.).
Inheritance Properties and Implementation
✓ Inheritance implements the IS-A relationship ( Rectangle is a Figure)
✓ The new class is called Derived / Child / Sub class and the existing class is known as the Base / Parent / Super class
✓ Sub / Derived / Child class is the class that inherits properties from another class.
✓ Super / Super class is the class whose properties are inherited.
✓ The derived class inherits all the properties (Attributes and Methods) of the base class, without changing the properties of base
class and may add new features to its own but we must consider the access specifiers of the class.
✓ These new features in the derived class will not affect the base class.
✓ A derived class doesn’t inherit access to private data members.
✓ When a base class is privately inherited by the derived class, public members of the base class becomes the private members of
the derived class and therefore, the public members of the base class can only be accessed by the member functions of the derived
class. They are inaccessible to the objects of the derived class.
✓ On the other hand, when the base class is publicly inherited by the derived class, public members of the base class also become
the public members of the derived class. Therefore, the public members of the base class are accessible by the objects of the
derived class as well as by the member functions of the derived class.
✓ For creating a sub-class that is inherited from the base class we have to follow the below syntax.
class <derived_class_name> : <visibility mode> <base_class_name>
{ //body }

✓ Visibility modes of the inheritance


▪ Public
▪ Private
▪ Protected
Inheritance Modes in C++.
▪ Public Mode
✓ Members (public / protected) of the base class will have the same accessibility in the derived class.
▪ Protected Mode
✓ Members (public / protected) of the base class will become protected in the derived class.
▪ Private Mode
✓ Members (public / protected) of the base class will become private in the derived class.
Note: The private member in the class is not inheritable
class A class A
class A
{ {
{
public: public:
public:
int x; int x;
int x;
protected: protected:
protected:
int y; int y;
int y;
private: private:
private:
int z; int z;
int z;

}; };
};
class B: protected A class B: private A
class B: public A
{ {
{
// x is protected // x is private
// x is public
// y is protected // y is private
// y is protected
// z is not accessible from C // z is not accessible from D
// z is not accessible from B
} }
}
Types of Inheritance in C++ (cont.).
Single inheritance Multilevel inheritance Hierarchical inheritance
✓ Derived class is inherited from only one base ✓ Deriving a class from another derived class. ✓ Deriving more than one class from a base class.
class that is not inherited from any other classes. class A
class A
{
class A {
};
{ }
class B: public A
}; class B : public A
{
class B: public {
};
A }
class C: public B
{ class C : public A
{
} {
};
}
class D : public A
{
}
Multiple inheritance Hybrid inheritance
✓ Deriving a new class that inherits from two or more classes. ✓ Combination of more than one type of inheritance.
class A class A
{ {
}; }
class B class B : public A
{ {
}; }
class C: public A, public B class C : public A
{ {
}; }
class D : public B , public C
{
}
Inheritance Example.
#include<iostream> class Triangle : public Shape
using namespace std; {
class Shape public:
{ Triangle (float x, float y): Shape(x,y)
public: {
float a; }
float b; float triangle_area()
public: {
Shape(float n,float m) return (0.5*a*b);
{ }
a=n; };
b=m; int main()
} {
};
class Rectangle : public Shape int l,w,b,h;
{ cout << "Enter the length and width of a rectangle:" <<endl;
public: cin>>l>>w;
Rectangle (float x, float y): Shape(x,y) Rectangle r(l,w);
{ cout << "Area of the rectangle is:" <<r.rectangle_area()<<endl;
} cout << "Enter the base and height of the triangle:" <<endl;
int rectangle_area() cin>>b>>h;
{ Triangle t (b,h);
return (a*b); cout <<"Area of the triangle is:" <<t.triangle_area()<<endl;
} return 0;
}; }
Any Questions?????

You might also like