SlideShare une entreprise Scribd logo
1  sur  6
Brief Summary of C++ (Mainly on Class)
Attributes of OOP
    1) Encapsulation
            a. Hide the data (make the data variable private) and hide the internal
               function that is not needed by the external user
            b. Only exposes the functions that are required by the external user. User
               calls these public functions in order to use the object.
    2) Code reuse
            a. Use inheritance to reuse existing code
    3) Abstraction
          Use class to model the things you have in your program. Program consist of
       objects that talk to each other by calling each other public member function.
    4) Generalization
            a. Use template class or template function to build generic class or function
            b. Generic function can process different type of data
            c. Build a general class and use it as a base to derive specialized class
               (inheritance)


Variable
 - Refers to memory location used to store data
 - Is given a name example weight, myID . It is not convenient to memorize memory
     address e.g A1230000FFA

Variable data type can be classified to a few types

   a) Simple data type
      int, char , float, double
       int weight = 0; // declare and initialize the variable in 1 line
       of code.

   b) Array
      Array is a compound data type whereby it stores a group of data
       int weightArray[5] ; // declare an array called weightArray to
       store 5 integer type data
       int weightArray[5] ; // declare an array called weightArray to
       store up to 5 integer type data
       int weightArray2[5] = {1,2,3,4,5}; // You can also declare and
       initialize
       cout << endl << weightArray2[2] ; //% display the 3rd element

   c) Pointer
      Pointer is a type of variable that is used to represent other variable
      It is mainly used to represent an array, object and also to pass data to a function
      by reference. In addition the function can pass data to the pointer so that it can be
      retrieved by the caller function.
      Pointer stores the address of the variable that it points to.



                                                                                            1
int* ptr ; // declare a pointer to int and name the pointer as
   ptr
   int* ptr2 = &weight ; // declare a pointer to int and initialize
   it to point to the variable weight in 1 line of code
   ptr = &weight2 ; // The previously declared pointer is now
   pointed at the variable weight2
   cout << endl << *ptr2 << endl ; // display the data in the
   variable pointed by ptr2, display 0 since weight=0

   Using pointer to represent array

   int* arrayPtr;
   arrayPtr = weightArray2 ;           //arrayPtr now points to the array
                                        // weightArray2
                                      // take note that the array name hold
                                          the address of the array

   cout <<    endl << arrayPtr ; // display the address of the 1st
   element
   cout <<    endl << arrayPtr+1 ; //         display the address of the 2nd
   element
   cout <<    endl   <<   *(arrayPtr) ;   // display 1
   cout <<    endl   <<   *(arrayPtr+1)   ; // display 2
   cout <<    endl   <<   arrayPtr[0] ;   // display 1
   cout <<    endl   <<   arrayPtr[1] ;   // display 2

   char* mystring = "Hello" ;
   cout << mystring;

   const int* pt = weightArray ; // pt is a pointer to a constant,
   you cannot use pt to change the value of weightArray
                                 // *(pt+1) = 200 ; this is wrong
   int* const pt2 = weightArray; // pt2 is a constant pointer, you
   cannot use pt2 to point to other variable, pt2 always represents
   weightArray // pt2 = weightArray2 , this is wrong


d) Reference
   Reference is a variable that represent other variable as an alias.
   It is mainly used to pass data to a function by reference. In addition the function
   can pass data to the reference variable so that it can be retrieved by the caller
   function.

   int& rnum = weight2; // declare a reference variable by the name
   rnum and initialize it to represent weight2
                                   // reference variable must always
   be initialized when it is first declared
   cout << endl << rnum ; // display 10, the value of weight2
   rnum = weight ;       // reassign rnum to represent the variable
   weight
   cout << endl << rnum ; // display 0, the value of weight

e) Class and Structure
   In C++ there are many predefined variable type such as int, char, float
   However you can also create your own data type using the class and struct
   construct.

                                                                                         2
Class is a c++ language construct that is used as a blueprint to create objects
Object is an instance of the class and is a variable.
Object contain member function and member variable. Member function provide
the service and member variable store data.
Member can be private , public, protected


// Declare a class by the name of Student
// the purpose or responsibility of Student class is to store
students information
// To fulfill its responsibility , it provides a set of services
to the user
// User can invoke the public member function for example
getCgpa() to retrieve the cgpa value stored in the object
class Student {

public:
      Student(); // default constructor
      Student(float p_cgpa) { _cgpa = p_cgpa ;} // parameterized
                                                constructor
      Student(string name);
      Student(string name, string address);
      float getCgpa(); // member function
      void set_CgpaAndAge( float p_cgpa, int p_age) {
        _cgpa = p_cgpa ;
      _age = p_age;
      }
      void setName(string pName) { _name = pName;}
      string getAddress();
      void getcgpaAndAge(float& p_cgpa, int& p_age);
private:
      string _name;
      string _address;
      char _icNumber[20];
      float _cgpa;
      int _age;
} ;

// Test program to test the class and its member function defined above
int main()
{

Student stud1("Lim"); // Create the object called stud1 and
initialize its name
stud1.set_CgpaAndAge(3.99,20); // set the cgpa value and age of
object stud1
}



Getting function to return more than one value

Suppose in the main function we want to retrieve the cgpa and age value of the
object, we cannot write a function to return 2 values. A function can only return 1
value. One way to solve this problem so that a function can pass more than 1

                                                                                  3
variable back to the caller function is to use the reference variable as the function
argument.

main( )
{ int x=0, y=0;
functionName(x,y) ;
cout << x << y ; // Display 100 200
}

void functionName (int& arg1, int& arg2)
{
arg1 = 100;
arg2 = 200;
}
This way the function functionName can return the 2 integer values 100, 200 back
to the main function. By using reference variable you can pass multiple data to a
function and also use it as container to store the data that need to be returned by
the function.

Here is the implementation for the Student class member function The main ()
function need to retrieve the cgpa value and the age value from the Student object
stud1.

1) Method 1 : Use a reference variable

       // the function below retrieve the data _cgpa and _age from
       the Student object and pass them to the reference variable
       so that the caller function can get hold of this data
       void Student::getcgpaAndAge(float& p_cgpa, int& p_age) {
       p_cgpa = _cgpa ;
       p_age = _age ; // assign member variable to argument
                      // variable
       }

       int main()
       {
       int age; float cgpa;
       Student stud1("Lim"); // Create the object called stud1 and
       initialize its name
       stud1.set_CgpaAndAge(3.99,20); // set the cgpa value and
       age of object stud1

       stud1.getcgpaAndAge(cgpa, age); // request the stud1
       object to get and return its cgpa value and age value

       cout << endl << "cgpa = " << cgpa; // display 3.99
       cout << endl << " age = " << age;
       }




                                                                                        4
Program output
Output of object s4
Ali

Output of object s4 access using pointer
Ali

Output of object s4 access using reference
Ali

 Output of object ecpStudents[1]
ecpStudents[1]._name = Ah Kow

 Output of object ecpStudents[2] in the array , this time the array is represented using the
pointer pStd
 ecpStudents[2]._name = pStd[2]._name = Aminah

Use pointer pStd2 to represent the array of 3 Student objects, access the 2nd object
pStd2[1]._name = No name yet

This program allow the Student object to be added to the Subject object
Subject object has many Student object

Constructor called: Subject Name: ECP4206 OOP Programming

Number of Student are 2
Phua CK
Obama




                                                                                          5
6

Contenu connexe

Tendances

Tendances (20)

Ch2 Liang
Ch2 LiangCh2 Liang
Ch2 Liang
 
CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++CLASSES, STRUCTURE,UNION in C++
CLASSES, STRUCTURE,UNION in C++
 
Sql server difference faqs- 9
Sql server difference faqs- 9Sql server difference faqs- 9
Sql server difference faqs- 9
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Lecture21
Lecture21Lecture21
Lecture21
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
 
Lecture02
Lecture02Lecture02
Lecture02
 
JavaYDL11
JavaYDL11JavaYDL11
JavaYDL11
 
ccc
cccccc
ccc
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Fast Forward To Scala
Fast Forward To ScalaFast Forward To Scala
Fast Forward To Scala
 
Objectiveccheatsheet
ObjectiveccheatsheetObjectiveccheatsheet
Objectiveccheatsheet
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 

Similaire à Brief Summary Of C++

Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 

Similaire à Brief Summary Of C++ (20)

Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Link list
Link listLink list
Link list
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Overloading
OverloadingOverloading
Overloading
 
Lecture5
Lecture5Lecture5
Lecture5
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
C++ theory
C++ theoryC++ theory
C++ theory
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
Lecture5
Lecture5Lecture5
Lecture5
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 

Dernier

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Dernier (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

Brief Summary Of C++

  • 1. Brief Summary of C++ (Mainly on Class) Attributes of OOP 1) Encapsulation a. Hide the data (make the data variable private) and hide the internal function that is not needed by the external user b. Only exposes the functions that are required by the external user. User calls these public functions in order to use the object. 2) Code reuse a. Use inheritance to reuse existing code 3) Abstraction Use class to model the things you have in your program. Program consist of objects that talk to each other by calling each other public member function. 4) Generalization a. Use template class or template function to build generic class or function b. Generic function can process different type of data c. Build a general class and use it as a base to derive specialized class (inheritance) Variable - Refers to memory location used to store data - Is given a name example weight, myID . It is not convenient to memorize memory address e.g A1230000FFA Variable data type can be classified to a few types a) Simple data type int, char , float, double int weight = 0; // declare and initialize the variable in 1 line of code. b) Array Array is a compound data type whereby it stores a group of data int weightArray[5] ; // declare an array called weightArray to store 5 integer type data int weightArray[5] ; // declare an array called weightArray to store up to 5 integer type data int weightArray2[5] = {1,2,3,4,5}; // You can also declare and initialize cout << endl << weightArray2[2] ; //% display the 3rd element c) Pointer Pointer is a type of variable that is used to represent other variable It is mainly used to represent an array, object and also to pass data to a function by reference. In addition the function can pass data to the pointer so that it can be retrieved by the caller function. Pointer stores the address of the variable that it points to. 1
  • 2. int* ptr ; // declare a pointer to int and name the pointer as ptr int* ptr2 = &weight ; // declare a pointer to int and initialize it to point to the variable weight in 1 line of code ptr = &weight2 ; // The previously declared pointer is now pointed at the variable weight2 cout << endl << *ptr2 << endl ; // display the data in the variable pointed by ptr2, display 0 since weight=0 Using pointer to represent array int* arrayPtr; arrayPtr = weightArray2 ; //arrayPtr now points to the array // weightArray2 // take note that the array name hold the address of the array cout << endl << arrayPtr ; // display the address of the 1st element cout << endl << arrayPtr+1 ; // display the address of the 2nd element cout << endl << *(arrayPtr) ; // display 1 cout << endl << *(arrayPtr+1) ; // display 2 cout << endl << arrayPtr[0] ; // display 1 cout << endl << arrayPtr[1] ; // display 2 char* mystring = "Hello" ; cout << mystring; const int* pt = weightArray ; // pt is a pointer to a constant, you cannot use pt to change the value of weightArray // *(pt+1) = 200 ; this is wrong int* const pt2 = weightArray; // pt2 is a constant pointer, you cannot use pt2 to point to other variable, pt2 always represents weightArray // pt2 = weightArray2 , this is wrong d) Reference Reference is a variable that represent other variable as an alias. It is mainly used to pass data to a function by reference. In addition the function can pass data to the reference variable so that it can be retrieved by the caller function. int& rnum = weight2; // declare a reference variable by the name rnum and initialize it to represent weight2 // reference variable must always be initialized when it is first declared cout << endl << rnum ; // display 10, the value of weight2 rnum = weight ; // reassign rnum to represent the variable weight cout << endl << rnum ; // display 0, the value of weight e) Class and Structure In C++ there are many predefined variable type such as int, char, float However you can also create your own data type using the class and struct construct. 2
  • 3. Class is a c++ language construct that is used as a blueprint to create objects Object is an instance of the class and is a variable. Object contain member function and member variable. Member function provide the service and member variable store data. Member can be private , public, protected // Declare a class by the name of Student // the purpose or responsibility of Student class is to store students information // To fulfill its responsibility , it provides a set of services to the user // User can invoke the public member function for example getCgpa() to retrieve the cgpa value stored in the object class Student { public: Student(); // default constructor Student(float p_cgpa) { _cgpa = p_cgpa ;} // parameterized constructor Student(string name); Student(string name, string address); float getCgpa(); // member function void set_CgpaAndAge( float p_cgpa, int p_age) { _cgpa = p_cgpa ; _age = p_age; } void setName(string pName) { _name = pName;} string getAddress(); void getcgpaAndAge(float& p_cgpa, int& p_age); private: string _name; string _address; char _icNumber[20]; float _cgpa; int _age; } ; // Test program to test the class and its member function defined above int main() { Student stud1("Lim"); // Create the object called stud1 and initialize its name stud1.set_CgpaAndAge(3.99,20); // set the cgpa value and age of object stud1 } Getting function to return more than one value Suppose in the main function we want to retrieve the cgpa and age value of the object, we cannot write a function to return 2 values. A function can only return 1 value. One way to solve this problem so that a function can pass more than 1 3
  • 4. variable back to the caller function is to use the reference variable as the function argument. main( ) { int x=0, y=0; functionName(x,y) ; cout << x << y ; // Display 100 200 } void functionName (int& arg1, int& arg2) { arg1 = 100; arg2 = 200; } This way the function functionName can return the 2 integer values 100, 200 back to the main function. By using reference variable you can pass multiple data to a function and also use it as container to store the data that need to be returned by the function. Here is the implementation for the Student class member function The main () function need to retrieve the cgpa value and the age value from the Student object stud1. 1) Method 1 : Use a reference variable // the function below retrieve the data _cgpa and _age from the Student object and pass them to the reference variable so that the caller function can get hold of this data void Student::getcgpaAndAge(float& p_cgpa, int& p_age) { p_cgpa = _cgpa ; p_age = _age ; // assign member variable to argument // variable } int main() { int age; float cgpa; Student stud1("Lim"); // Create the object called stud1 and initialize its name stud1.set_CgpaAndAge(3.99,20); // set the cgpa value and age of object stud1 stud1.getcgpaAndAge(cgpa, age); // request the stud1 object to get and return its cgpa value and age value cout << endl << "cgpa = " << cgpa; // display 3.99 cout << endl << " age = " << age; } 4
  • 5. Program output Output of object s4 Ali Output of object s4 access using pointer Ali Output of object s4 access using reference Ali Output of object ecpStudents[1] ecpStudents[1]._name = Ah Kow Output of object ecpStudents[2] in the array , this time the array is represented using the pointer pStd ecpStudents[2]._name = pStd[2]._name = Aminah Use pointer pStd2 to represent the array of 3 Student objects, access the 2nd object pStd2[1]._name = No name yet This program allow the Student object to be added to the Subject object Subject object has many Student object Constructor called: Subject Name: ECP4206 OOP Programming Number of Student are 2 Phua CK Obama 5
  • 6. 6