You are on page 1of 32

20CS411 – DATA STRUCTURES USING C++

Title of Topic: Access Control - Constructors and destructors


Course Code: 20CS411
Course Title: Data Structures Using C++
Session Number: 1.7
Faculty Name: Ms. S. Padmavathi
Academic Year: 2021 – 2022 (Even Sem)

MODULE 1 1
20CS411 – DATA STRUCTURES USING C++

MODULE – 1

C++ PROGRAMMING
An overview of C++ - Difference between procedure and object oriented
programming language, Data Types, Variables, Operators, Expressions
and Statements-Functions and Arrays- C++ Class Overview- Class
Definition, Objects, Class Members, Access Control, Constructors and
destructors, parameter passing methods, Inline functions, static class
members, this pointer, friend functions, dynamic memory allocation and
deallocation (new and delete) - Inheritance basics, base and derived
classes, inheritance types, runtime polymorphism using virtual functions,
abstract classes - Generic Programming- Function and class templates.

MODULE 1 2
20CS411 – DATA STRUCTURES USING C++

MODULE 1 - C++ PROGRAMMING

1.1 An overview of C++ - Difference between procedure and object


oriented programming language
1.2 Data Types, Variables

1.3 Operators, Expressions and Statements

1.4 Functions

1.5 Arrays
1.6 C++ Class Overview- Class Definition, Objects, Class Members

1.7 Access Control - Constructors and destructors

1.8 Parameter passing methods, Inline functions

MODULE 1 3
20CS411 – DATA STRUCTURES USING C++

MODULE 1 - C++ PROGRAMMING

1.9 Static class members, this pointer

1.10 Friend functions, dynamic memory allocation and deallocation (new

and delete)
1.11 Inheritance basics, base and derived classes, inheritance types

1.12 Runtime polymorphism using virtual functions

1.13 Abstract classes


1.14 Generic Programming- Function and class templates

MODULE 1 4
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control

• One of the main features of object-oriented programming


languages such as C++ is data hiding.
• Access Modifiers or Access Specifiers in a class are used to
assign the accessibility to the class members.
• The access specifiers used in C++ are Private, Protected
and Public.

MODULE 1 5
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control

Public
• Members are accessible from outside the class using the
direct member access operator (.) with the object of that
class. 
Private
• Only the member functions or the friend functions are
allowed to access the private data members of a class.
• Members cannot be accessed (or viewed) from outside the
class
Protected
• Members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.

MODULE 1 6
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control

By default the access modifier for the members will be Private


Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};

MODULE 1 7
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control

Predict the Output:


class MyClass {
  public:    // Public access specifier
    int x;   // Public attribute
  private:   // Private access specifier
    int y;   // Private attribute
};

int main() {
  MyClass myObj;
  myObj.x = 25;  
  myObj.y = 50;  
  return 0;
}
MODULE 1 8
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Public

• The public keyword is used to create public members


(data and functions).
• Members are accessible from inside the class and outside
the class
class PublicAccess {
// public access modifier
public:
int x; // Data Member Declaration
void display(); // Member Function declaration
}

MODULE 1 9
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Public


Example
#include<iostream> // main function
using namespace std; int main()
  {
// class definition     Circle obj;
class Circle      
{     // accessing public datamember
    public: outside class
        double radius;     obj.radius = 5.5;
               
        double  compute_area() cout << "Radius is: " << obj.radius
        { << "\n";
            return 3.14*radius*radius; cout << "Area is: " <<
        }       obj.compute_area();
};     return 0;
  }

MODULE 1 10
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Private

•The private keyword is used to create private members (data and


functions).
•The private members can only be accessed from within the class.
•However, friend classes and friend functions can access private
members.

MODULE 1 11
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Private


#include<iostream>  
using namespace std;
 
class Circle // main function
{   int main()
    // private data member {  
    private:     // creating object of the class
        double radius;     Circle obj;
            
    // public member function        // trying to access private data
    public:    member
        double  compute_area()     // directly outside the class
        {   // member function can     obj.radius = 1.5;
access private      
            // data member radius     cout << "Area is:" <<
            return 3.14*radius*radius; obj.compute_area();
        }           return 0;
}; }
MODULE 1 12
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Private

• The output of above program is a compile time error


because we are not allowed to access the private data
members of a class directly outside the class.
• Yet an access to obj.radius is attempted, radius being a
private data member we obtain a compilation error. 

• However, we can access the private data members of a


class indirectly using the public member functions of the
class. 
MODULE 1 13
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Private


#include<iostream> endl;
using namespace std;             cout << "Area is: " << area;
          } };
class Circle  
{   // main function
    // private data member int main()
    private: {  
        double radius;     // creating object of the class
           Circle obj;
    // public member function         
    public:        // trying to access private data
        void compute_area(double r) member
        {   // member function can access     // directly outside the class
private     obj.compute_area(1.5);
            // data member radius      
            radius = r;      
                  return 0;
 double area = 3.14*radius*radius; }
             
cout << "Radius is: " << radius <<
MODULE 1 14
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Protected

• Protected access modifier is similar to private access modifier


• It can’t be accessed outside of it’s class unless with the help of
friend class
• The class members declared as Protected can be accessed by
within the class and from the derived class. 

Note: This access through inheritance can alter the access


modifier of the elements of base class in derived class depending
on the modes of Inheritance

MODULE 1 15
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control – Protected


#include <iostream>         id_protected = id; }
using namespace std;      
      void displayId()
// base class     {
class Parent         cout << "id_protected is: " <<
{       // protected data members id_protected << endl;
    protected:     } };
    int id_protected;       
}; // main function
 // sub class or derived class from int main() {
public base class      
class Child : public Parent     Child obj1;
{      
    public:     // member function of the derived
    void setId(int id) class can
    {             // access the protected data
        members of the base class
// Child class is able to access the      
inherited     obj1.setId(81);
 // protected data members of base     obj1.displayId();
class     return 0;
         
MODULE 1 } 16
20CS411 – DATA STRUCTURES USING C++

1.7 Access Control

MODULE 1 17
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor

Constructor :
• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is
created.
• It must be placed in public section of class.
• If we do not specify a constructor, C++ compiler generates
a default constructor for object (expects no parameters and
has an empty body).
• Declare a constructor as protected or private.
MODULE 1 18
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor

Types of Constructor in C++

MODULE 1 19
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor
Default Constructor :
• No parameter
• Invoked at the time of creating object.
• If no constructors are declared in a class, the compiler
provides an implicit inline default constructor.

MODULE 1 20
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor
#include <iostream> Constructor Program
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{ Output:
Employee e1; Default Constructor Invoked
Employee e2; Default Constructor Invoked
return 0;
}

MODULE 1 21
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor

Parameterized Constructor
• Constructors with parameter
• Different values to data members of different objects
• Passing the appropriate values as argument.
• Take parameters (just like regular functions)
class Cube
{
public:
int side;
Cube(int x) // Parameterized Constructor
{
side=x;
}
};

MODULE 1 22
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor
Parameterized Constructor Program
#include <iostream> void display()
using namespace std; {
class Employee { cout<<id<<" "<<name<<"
public: "<<salary<<endl;
int id; }
string name; };
float salary; int main(void) {
Employee(int i, string n, float s) Employee e1 =Employee(101,
{ "Sonoo", 890000);
id = i; Employee e2=Employee(102, "Nakul",
name = n; 59000);
salary = s; e1.display();
} e2.display();
return 0;
}

MODULE 1 23
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor

Copy Constructor :
• Copy values of data members of one object into other
object
• Constructors which takes an object as argument

classname (const classname &obj)


{
Example : // body of constructor
}

MODULE 1 24
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor

Copy Constructor Program


#include<iostream> int getX()
using namespace std; {
class test return x;
{ }
private: };
int x;
public: int main()
test(int x1) {
{ test t1(7); // Normal constructor is
x = x1; called here
} test t2 = t1; // Copy constructor is
test(const test &t2) called here
{ cout << "t1.x = " << t1.getX();
x = t2.x; cout << "nt2.x = " << t2.getX();
} return 0;
}
MODULE 1 25
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor
Constructor Overloading
• Overloaded constructors must have the same name and
different number of arguments
• Overloading achieved based on the number of parameter and
types of the arguments are passed.
•  Argument is passed while creating objects

class Rect{
private:
int area;
public:
Rect(){ area = 0; }
Rect(int a, int b){ area = a * b; }

MODULE 1 26
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor
Constructor Overloading Program
class Student
{ int main()
public: {
int rollno; Student A(10);
string name; Student B(11, "John");
// first constructor }
Student(int x)
{
rollno = x;
name = "None";
}
// second constructor
Student(int x, string str)
{
rollno = x;
name = str;
}
};
MODULE 1 27
20CS411 – DATA STRUCTURES USING C++

1.7 Destructor

• Destructs the objects of classes


• It is defined like constructor.
• It must have same name as class
• Prefixed with a tilde sign (~)
• Don’t take any argument and don’t return anything

~class_name()
Syntax {
//Some code
}

MODULE 1 28
20CS411 – DATA STRUCTURES USING C++

1.7 Destructor

Destructor Program
class A
{ int main()
// constructor {
A() A obj1; // Constructor Called
{ int x = 1
cout << "Constructor called"; if(x)
} {
A obj2; // Constructor Called
// destructor } // Destructor Called for obj2
~A() } // Destructor Called for obj1
{
cout << "Destructor called";
}
};

MODULE 1 29
20CS411 – DATA STRUCTURES USING C++

1.7 Constructor

MODULE 1 30
20CS411 – DATA STRUCTURES USING C++

Try Yourself

1. Imagine a tollbooth with a class called toll Booth. The two data
items are a type unsigned int to hold the total number of cars,
and a type double to hold the total amount of money collected. A
constructor initializes both these to 0. A member function called
payingCar ( ) increments the car total and adds 0.50 to the cash
total. Another function, called nopayCar ( ), increments the car
total but adds nothing to the cash total. Finally, a member
function called displays the two totals.
2. Write a C++ program to generate Fibonacci Series. Use
Constructor to Initialize the Data Members.

MODULE 1 31
20CS411 – DATA STRUCTURES USING C++

Try Yourself

1. Write a program to perform addition of two complex numbers


using constructor overloading. The first constructor which takes
no argument is used to create objects which are not initialized,
second which takes one argument is used to initialize real and
imag parts to equal values and third which takes two argument
is used to initialized real and imag to two different values.

MODULE 1 32

You might also like