0% found this document useful (0 votes)
33 views

Object Oriented Programming: Lab Manual Pointers

this is lab manual

Uploaded by

Hanzla Salfi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Object Oriented Programming: Lab Manual Pointers

this is lab manual

Uploaded by

Hanzla Salfi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

NAME: HANZLA SALFI

ROLL NO: BSEM-S21-012

OBJECT ORIENTED PROGRAMMING


Lab Manual
POINTERS
A pointer however, is a variable that stores the memory address as its
value.

A pointer variable points to a data type (like int or string) of the same type,


and is created with the * operator. The address of the variable you're working
with is assigned to the pointer:

Like any variable or constant, you must declare a pointer before you can work with it.
The general form of a pointer variable declaration is −
type *var-name;

#include <iostream>
using namespace std;
int main() {
int x = 27;
int *ip;
ip = &x;
cout << "Value of x is : ";
cout << x << endl;
cout << "Value of ip is : ";
cout << ip<< endl;
cout << "Value of *ip is : ";
cout << *ip << endl;
return 0;
}
CODE EXPLAINATION:

o Import the iostream header file. This will allow us to use the functions defined in
the header file without getting errors.
o Include the std namespace to use its classes without calling it.
o Call the main() function. The program logic should be added within the body of
this function. The { marks the beginning of the function’s body.
o Declare an integer variable x and assigning it a value of 27.
o Declare a pointer variable *ip.
o Store the address of variable x in the pointer variable.
o Print some text on the console.
o Print the value of variable x on the screen.
o Print some text on the console.
o Print the address of variable x. The value of the address was stored in the
variable ip.
o Print some text on the console.
o Print value of stored at the address of the pointer.
o The program should return value upon successful execution.
o End of the body of the main() function.
Pointers to Constant

In the pointers to constant, the data pointed by the pointer is constant and cannot be
changed. Although, the pointer itself can change and points somewhere else (as the
pointer itself is a variable).
EXAMPLE:
#include <iostream>
using namespace std;

int main()
{
int high{ 100 };
int low{ 66 };
const int* score{ &high };

// Pointer variable are read from


// the right to left
cout << *score << "\n";

// Score is a pointer to integer


// which is constant *score = 78

// It will give you an Error:


// assignment of read-only location
// ‘* score’ because value stored in
// constant cannot be changed
score = &low;

// This can be done here as we are


// changing the location where the
// score points now it points to low
cout << *score << "\n";

return 0;
}
Constant Pointers

In constant pointers, the pointer points to a fixed memory location and the value
at that location can be changed because it is a variable, but the pointer will
always point to the same location because it is made constant here.

Example:

#include <iostream>
using namespace std;

int main()
{
int a{ 90 };
int b{ 50 };
int* const ptr{ &a };
cout << *ptr << "\n";
cout << ptr << "\n";
// Address what it points to
*ptr = 56;
// Acceptable to change the value of a
// Error: assignment of read-only
// variable ‘ptr’
// ptr = &b;
cout << *ptr << "\n";
cout << ptr << "\n";
return 0;
}

Constant Pointers To Constant

In the constant pointers to constants, the data pointed to by the pointer is


constant and cannot be changed. The pointer itself is constant and cannot
change and point somewhere else.

Example:

#include <iostream>
using namespace std;

int main()
{
const int a{ 50 };
const int b{ 90 };
// ptr points to a
const int* const ptr{ &a };
// *ptr = 90;
// Error: assignment of read-only // location ‘*(const int*)ptr’
// ptr = &b;
// Error: assignment of read-only // variable ‘ptr’
// Address of a
cout << ptr << "\n";
// Value of a
cout << *ptr << "\n";
return 0;
}

ARRAYS

Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:

DataType cars[4];

One-Dimensional Array

A one-dimensional array (or single dimension array) is a type of linear array.
Accessing its elements involves a single subscript which can either represent a row or
column index. ... Here, the array can store ten elements of type int . This array has
indices starting from zero through nine.

Example:

#include<iostream>
using namespace std;
void sum(int a[], int b[])
{
int add[5];
for(int i=0 ; i<5 ; i++)
{
add[i]=a[i]+b[i];
cout<<add[i]<<" ";
}
}
int main ()
{
int a[5]={3,7,8,9,8};
int b[5]={3,7,8,9,8};
sum(a,b);
}
Two-Dimensional Array

The two-dimensional array can be defined as an array of arrays. The 2D array is


organized as matrices which can be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database lookalike data
structure.

Example:

#include<iostream>
using namespace std;

int main()
{
// an array with 3 rows and 2 columns.
int x[3][2] = {{0,1}, {2,3}, {4,5}};
// output each array element's value
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "Element at x[" << i
<< "][" << j << "]: ";
cout << x[i][j]<<endl;
}
}

return 0;
}
To output all the elements of a Two-Dimensional array we can use nested for loops.
We will require two for loops. One to traverse the rows and another to traverse
columns.

Three-Dimensional Array

A 3D array is a multi-dimensional array(array of arrays). A 3D array is a collection


of 2D arrays . It is specified by using three subscripts:Block size, row size and column
size. More dimensions in an array means more data can be stored in that array.

Example:

// C++ program to print elements of Three-Dimensional


// Array
#include<iostream>
using namespace std;

int main()
{
// initializing the 3-dimensional array
int x[2][3][2] =
{
{ {0,1}, {2,3}, {4,5} },
{ {6,7}, {8,9}, {10,11} }
};
// output each element's value
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
cout << "Element at x[" << i << "][" << j
<< "][" << k << "] = " << x[i][j][k]
<< endl;
}
}
}
return 0;
}

Accessing elements in Three-Dimensional Arrays is also similar to that of Two-


Dimensional Arrays. The difference is we have to use three loops instead of two loops
for one additional dimension in Three-dimensional Arrays.

In similar ways, we can create arrays with any number of dimension. However
the complexity also increases as the number of dimension increases.
The most used multidimensional array is the Two-Dimensional Array.
CLASSES

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.

Create a Class:

Create a class called “My Class”:

class MyClass {       // The class


  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

explained

 The class keyword is used to create a class called MyClass.


 The public keyword is an access specifier, which specifies that members
(attributes and methods) of the class are accessible from outside the class. You
will learn more about access specifiers later.
 Inside the class, there is an integer variable myNum and a string
variable myString. When variables are declared within a class, they are
called attributes.
 At last, end the class definition with a semicolon ;.

Create an Object:

In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes (myNum and myString), use the dot syntax (.) on the
object:

Create an object called “myObj”:


class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};
int main() {
  MyClass myObj;  // Create an object of MyClass
  // Access attributes and set values
  myObj.myNum = 15; 
  myObj.myString = "Some text";
  // Print attribute values
  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  return 0;
}

You can also create multiple objects of one class.

Example:

#include<iostream>
using namespace std;

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
In the above code we created a class of name “MYClass” and use the “public” access
specifier and make two attributes. In main we created an object “myObj” and then
assign the values and later cout to display them.

CONSTRUCTOR

A constructor is a special type of member function of a class which initializes


objects of a class. In C++, Constructor is automatically called when
object(instance of class) create. It is special member function of the class
because it does not have any return type.
 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).

DEFAULT CONSTRUCTOR: A default constructor is a constructor that either


has no parameters, or if it has parameters, all the parameters have default
values
CONSTRUCTOR PARAMETER: Constructors can also take parameters (just
like regular functions), which can be useful for setting initial values for attributes

Example:
class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z) { // Constructor with parameters
      brand = x;
      model = y;
      year = z;
    }
};

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values


  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}
DESTRUCTOR

Destructor is an instance member function which is invoked automatically


whenever an object is going to be destroyed. Meaning, a destructor is the last
function that is going to be called before an object is destroyed.
The thing is to be noted here, if the object is created by using new or the
constructor uses new to allocate memory which resides in the heap memory or
the free store, the destructor should use delete to free the memory. 
SYNATAX:

~constructor-name();

ACCESS SPECIFIER

The public keyword is an access specifier. Access specifiers define how the


members (attributes and methods) of a class can be accessed. In the example
above, the members are public - which means that they can be accessed and
modified from outside the code.

However, what if we want members to be private and hidden from the outside
world?

In C++, there are three access specifiers:

 public - members are accessible from outside the class


 private - 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.

Public:

All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be
accessed by other classes and functions too. The public members of a class
can be accessed from anywhere in the program using the direct member
access operator (.) with the object of that class.

Example:

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

The class members declared as private can be accessed only by the member


functions inside the class. They are not allowed to be accessed directly by any
object or function outside the class. Only the member functions or the friend
functions are allowed to access the private data members of a class. 

Example:

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

Output:

Error;
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
 
Protected:

Protected access modifier is similar to private access modifier in the sense that
it can’t be accessed outside of it’s class unless with the help of friend class, the
difference is that the class members declared as Protected can be accessed by
any subclass(derived class) of that class as well. 

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.

Example:
#include <bits/stdc++.h>
using namespace std;
 
// base class
class Parent
{  
    // protected data members
    protected:
    int id_protected;
    
};
 
// sub class or derived class from public base class
class Child : public Parent
{
    public:
    void setId(int id)
    {
         
        // Child class is able to access the inherited
        // protected data members of base class
         
        id_protected = id;
         
    }
     
    void displayId()
    {
        cout << "id_protected is: " << id_protected << endl;
    }
};
 
// main function
int main() {
     
    Child obj1;
     
    // member function of the derived class can
    // access the protected data members of the base class
     
    obj1.setId(81);
    obj1.displayId();
    return 0;
}

INHERITANCE

In C++, it is possible to inherit attributes and methods from one class to another.
We group the "inheritance concept" into two categories:

 derived class (child) - the class that inherits from another class


 base class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

TYPES OF INHERITANCE

 Single Inheritance
 Multi-level Inehritance
 Multiple Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Single Inheritance:
Single inheritance is one in which the derived class inherits the single base
class either publicly, privately or protectedly. In single inheritance, the
derived class uses the features or members of the single base class.
Example:

#include <bits/stdc++.h>
using namespace std;

// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};

int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Multilevel Inheritance

A class can also be derived from one class, which is already derived from
another class.

In the following example, MyGrandChild is derived from class MyChild (which is


derived from MyClass).

Example:

// Base class (parent)


class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Derived class (child)


class MyChild: public MyClass {
};

// Derived class (grandchild)


class MyGrandChild: public MyChild {
};

int main() {
  MyGrandChild myObj;
  myObj.myFunction();
  return 0;
}

MULTIPLE INHERITANCE

A class can also be derived from more than one base class, using a comma-
separated list:

Example:

#include <bits/stdc++.h>
using namespace std;

// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Another base class


class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}

HIERARCHICAL INHERITANCE
Hierarchical inheritance is a kind of inheritance where more than one class is
inherited from a single parent or base class. Especially those features which are
common in the parent class is also common with the base class.

Synatax;

class Parent_classname
{
Common_properties;
methods;
};
class derived_class1:visibility_mode parent_classname
{
Common_properties;
methods;
};
class derived_class2:visibility_mode parent_classname
{
Common_ properties;
methods;
};
.
.
.
.
class derived_classN:visibility_mode parent_classname
{
Common_properties;
methods;
};

HYBRID INHERITANCE

It is a combination of more than one type of inheritance. For example, it can be


achieved with a combination of both multilevel and hierarchical inheritance. This
type of inheritance is sometimes also called multipath inheritance.

SYNTAX:

Class Base
{
// body of Base class
};// end of Base class
class Derived1: access_mode Base
{
// access_mode can be public, private or protected
//body of Derived1 class which inherit property from base class
}; // end of class Derived1
Class Derived2: access_mode Base
{
// access_mode can be public, private or protected
//body of Derived2 class which inherit property from Base class
};//end of class Derived2
Class Derived3: access_mode Derived1, access_mode Derived2
{
// access_mode can be public, private or protected
//body of Derived3 class which inherit property from both Derived1 and Derived2
class.
};//end of class Derived3

You might also like