Friday 17 February 2023

Object and Class

 

Unit 2: Object and Class (16) 

 

2.1     Concept of Object and Class

2.2     Define Data Member and Member Function

2.3     Create object and access Member Function

2.4     Making outer function inline

2.5     Array with in Class

2.6     Array of Objects

2.7     Static Data Member and Static Function

2.8     Friends Functions

2.9     Concept of Constructor and Destructor

2.10   Empty, Parameterized and Copy constructor

2.11   Define Destructor

Practical Works:

·       Create class and objects with data member and member function. 

·       Declare and define member function and data member with visibility.

·       Create static function

·       Create friend functions.

·       Create different types of constructors

 

2.1  Concept of Object and Class

2073(2): Explain the concept of class and object with examples.

Objects are the run-time entities in object oriented system. Everything in C++ is associated with classes and objects. Along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the class. These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a "blueprint" for creating objects.

Write a C++ Program to find Largest among 3 numbers using classes and object

 

#include<iostream>
using namespace std;
class greatest
{
        private:
                int x,y,z;
        public:
        void input()
        {
                cout<<"Enter 3 nos.";
                cin>>x>>y>>z;
        }
        void calc()
        {
                int r;
                r=((x>y)&&(x>z)?x:(y>x)&&(y>z)?y:z);
                cout<<"Greatest no:"<<r;
        }
};
int main()
{
        greatest g;
        g.input();
        g.calc();
        
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2.2  Define Data Member and Member Function 
Data member: 
1.     The variable declared inside class are known as data members.
2.     Data member may be private or public.
      Member function: 
1.     The functions declared inside the class are known as member functions.
2.     Member functions are methods or functions that are defined inside of objects.
3.     Generally used to manipulate data members and other object data.
 

 

#include<iostream>
using namespace std;
class student
{
        private:
                int id;// data member
                char name[20]; // data member 
 
        public:
 
        void getdata(void)//member function
        void display(void)//member function
        {
                cout<<id<<’\t’<<name<<endl;
                
        }
        
};
int main()
{
        student s;
        s.getdata(void);
        s.display(void);
        
}

 

 

2.3  Create object and access Member Function

 

Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class.

If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution:: operator along with class name along with function name.

For example:

class Cube

{

    public:

    int side;

    /*

        Declaring function getVolume

        with no argument and return type int.

    */

    int getVolume();  

 

};

If we define the function inside class then we don't not need to declare it first, we can directly define the function.

class Cube

{

    public:

    int side;

    int getVolume()

    {

        return side*side*side;      //returns volume of cube

    }

};

But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside.

class Cube

{

    public:

    int side;

    int getVolume();

}

 

// member function defined outside class definition

int Cube :: getVolume()

{

    return side*side*side;

}

The main function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot . operator.

 

2.4  Making outer function inline

Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small.
The syntax for defining the function inline is:

inline return-type function-name(parameters)
{
    // function code
}  

The following program demonstrates the use of use of inline function.

#include <iostream>

using namespace std;

inline int cube(int s)

{

    return s*s*s;

}

int main()

{

    cout << "The cube of 3 is: " << cube(3) << "\n";

    return 0;

} //Output: The cube of 3 is: 27

 

2.5  Array with in Class

Array can be declared as the member of a class. The arrays can be declared as private, public or protected members of class.

C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays

To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows −

type arrayName [ arraySize ];

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement −

double balance[10];

Initializing Arrays

You can initialize C++ array elements either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

You will create exactly the same array as you did in the previous example.

balance[4] = 50.0;

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above −

Array Presentation

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable.

A program to demonstrate the concept of arrays as class members

Example:

#include<iostream>
 
const int size=5;
 
class student
 
{
 
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;
 
void student :: getdata ()
{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
 
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
 
void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

Output:

Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343

2.6 Array of Objects

When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.

 

 

Syntax:

ClassName ObjectName[number of objects];

The Array of Objects stores objects. An array of a class type is also known as an array of objects.

Example#1: 
Storing more than one Employee data. Let’s assume there is an array of objects for storing employee data emp[30].

Array of objects

#include<iostream>

using namespace std;

 

class Employee

{

  int id;

  char name[30];

  public:

   

  // Declaration of function

  void getdata();

   

  // Declaration of function

  void putdata();

};

 

// Defining the function outside

// the class

void Employee::getdata()

{

  cout << "Enter Id : ";

  cin >> id;

  cout << "Enter Name : ";

  cin >> name;

}

 

// Defining the function outside

// the class

void Employee::putdata()

{

  cout << id << " ";

  cout << name << " ";

  cout << endl;

}

 

// Driver code

int main()

{

  // This is an array of objects having

  // maximum limit of 30 Employees

  Employee emp[30];

  int n, i;

  cout << "Enter Number of Employees - ";

  cin >> n;

   

  // Accessing the function

  for(i = 0; i < n; i++)

    emp[i].getdata();

   

  cout << "Employee Data - " << endl;

   

  // Accessing the function

  for(i = 0; i < n; i++)

    emp[i].putdata();

}

Output:

https://media.geeksforgeeks.org/wp-content/uploads/20211028224555/Screenshot259.png

No comments:

Post a Comment