Object Oriented Programming: Lab Manual Pointers
Object Oriented Programming: Lab Manual Pointers
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 };
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;
}
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
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
Example:
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;
}
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.
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:
explained
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:
Example:
#include<iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
CONSTRUCTOR
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);
~constructor-name();
ACCESS SPECIFIER
However, what if we want members to be private and hidden from the outside
world?
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:
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:
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.
Example:
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." ;
}
};
// 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
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