C and C++ programming language

This page contains a collection examples on basic concepts of C programming like: loops, functions, pointers, structures etc.

Menu

  • Home
  • c programing
  • C++ programming
  • About us
  • Disclaimer
  • Privacy Policy
  • Terms and conditions
  • Contact us

Tuesday, October 23, 2018

C++ Classes and Objects

C++ Classes and Objects

In this article, you will learn to work with objects and classes in C++ programming.
C++ is a multi-paradigm programming language. Meaning, it supports different programming styles.
One of the popular ways to solve a programming problem is by creating objects, known as object-oriented style of programming.
C++ supports object-oriented (OO) style of programming which allows you to divide complex problems into smaller sets by creating objects.
Object is simply a collection of data and functions that act on those data.

C++ Class

Before you create an object in C++, you need to define a class.
A class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
As, many houses can be made from the same description, we can create many objects from a class.

How to define a class in C++?

A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
class className
   {
   // some data
   // some functions
   };

Example: Class in C++

class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };
Here, we defined a class named Test.
This class has two data members: data1and data2 and two member functions: function1() and function2().

Keywords: private and public

You may have noticed two keywords: private and public in the above example.
The private keyword makes data and functions private. Private data and functions can be accessed only from inside the same class.
The public keyword makes data and functions public. Public data and functions can be accessed out of the class.
Here, data1 and data2 are private members where as function1() and function2() are public members.
If you try to access private data from outside of the class, compiler throws error. This feature in OOP is known as data hiding.

C++ Objects

When 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 to Define Object in C++

className objectVariableName;
You can create objects of Test class (defined in above example) as follows:

class Test
{
    private:
        int data1;
        float data2;  

    public:  
        void function1()
        {   data1 = 2;  } 

        float function2()
        { 
            data2 = 3.5;
            return data2;
        }
   };

int main()
{
    Test o1, o2;
}
Here, two objects o1 and o2 of Testclass are created.
In the above class Test, data1 and data2are data members and function1() and function2() are member functions.

How to access data member and member function in C++?

You can access the data members and member functions by using a . (dot) operator. For example,
o2.function1();
This will call the function1() function inside the Test class for objects o2.
Similarly, the data member can be accessed as:
o1.data2 = 5.5;
It is important to note that, the private members can be accessed only from inside the class.
So, you can use o2.function1(); from any function or class in the above example. However, the code o1.data2 = 5.5; should always be inside the class Test.

Example: Object and Class in C++ Programming

// Program to illustrate the working of objects and class in C++ Programming
#include <iostream>
using namespace std;

class Test
{
    private:
        int data1;
        float data2;

    public:
       
       void insertIntegerData(int d)
       {
          data1 = d;
          cout << "Number: " << data1;
        }

       float insertFloatData()
       {
           cout << "\nEnter data: ";
           cin >> data2;
           return data2;
        }
};

 int main()
 {
      Test o1, o2;
      float secondDataOfObject2;

      o1.insertIntegerData(12);
      secondDataOfObject2 = o2.insertFloatData();

      cout << "You entered " << secondDataOfObject2;
      return 0;
 }
Output
Number: 12
Enter data: 23.3
You entered 23.3
In this program, two data members data1and data2 and two member functions insertIntegerData() and insertFloatData() are defined under Test class.
Two objects o1 and o2 of the same class are declared.
The insertIntegerData() function is called for the o1 object using:
o1.insertIntegerData(12);
This sets the value of data1 for object o1to 12.
Then, the insertFloatData() function for object o2 is called and the return value from the function is stored in variable secondDataOfObject2 using:
secondDataOfObject2 = o2.insertFloatData();
In this program, data2 of o1 and data1of o2 are not used and contains garbage value.
- October 23, 2018 No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels: CPP OBJECT AND CLASS, CPP programming

C++ Constructors

C++ Constructors

In this article, you'll learn about constructors in C++. You'll learn what is a constructor, how to create it and types of constructors in C++.
A constructor is a special type of member function that initialises an object automatically when it is created.
Compiler identifies a given member function is a constructor by its name and the return type.
Constructor has the same name as that of the class and it does not have any return type. Also, the constructor is always public.
... .. ...
class temporary
{
private: 
 int x;
 float y;
public:
 // Constructor
 temporary(): x(5), y(5.5)
 {
  // Body of constructor
 }
 ... ..  ...
};

int main()
{
 Temporary t1;
 ... .. ...
}
Above program shows a constructor is defined without a return type and the same name as the class.

How constructor works?

In the above pseudo code, temporary() is a constructor.
When an object of class temporary is created, the constructor is called automatically, and x is initialized to 5 and y is initialized to 5.5.
You can also initialise the data members inside the constructor's body as below. However, this method is not preferred.
temporary()
{
   x = 5;
   y = 5.5;
}
// This method is not preferred.

Use of Constructor in C++

Suppose you are working on 100's of Person objects and the default value of a data member age is 0. Initialising all objects manually will be a very tedious task.
Instead, you can define a constructor that initialises age to 0. Then, all you have to do is create a Person object and the constructor will automatically initialise the age.
These situations arise frequently while handling array of objects.
Also, if you want to execute some code immediately after an object is created, you can place the code inside the body of the constructor.

Example 1: Constructor in C++

Calculate the area of a rectangle and display it.
#include <iostream>
using namespace std;

class Area
{
    private:
       int length;
       int breadth;

    public:
       // Constructor
       Area(): length(5), breadth(2){ }

       void GetLength()
       {
           cout << "Enter length and breadth respectively: ";
           cin >> length >> breadth;
       }

       int AreaCalculation() {  return (length * breadth);  }

       void DisplayArea(int temp)
       {
           cout << "Area: " << temp;
       }
};

int main()
{
    Area A1, A2;
    int temp;

    A1.GetLength();
    temp = A1.AreaCalculation();
    A1.DisplayArea(temp);

    cout << endl << "Default Area when value is not taken from user" << endl;

    temp = A2.AreaCalculation();
    A2.DisplayArea(temp);

    return 0;
}
In this program, class Area is created to handle area related functionalities. It has two data members length and breadth.
A constructor is defined which initialises length to 5 and breadth to 2.
We also have three additional member functions GetLength(), AreaCalculation() and DisplayArea() to get length from the user, calculate the area and display the area respectively.
When, objects A1 and A2 are created, the length and breadth of both objects are initialized to 5 and 2 respectively, because of the constructor.
Then, the member function GetLength() is invoked which takes the value of lengthand breadth from the user for object A1. This changes the length and breadth of the object A1.
Then, the area for the object A1 is calculated and stored in variable temp by calling AreaCalculation() function and finally, it is displayed.
For object A2, no data is asked from the user. So, the length and breadth remains 5 and 2 respectively.
Then, the area for A2 is calculated and displayed which is 10.
Output
Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10

Constructor Overloading

Constructor can be overloaded in a similar way as function overloading.
Overloaded constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called.
Since, there are multiple constructors present, argument to the constructor should also be passed while creating an object.

Example 2: Constructor overloading

// Source Code to demonstrate the working of overloaded constructors
#include <iostream>
using namespace std;

class Area
{
    private:
       int length;
       int breadth;

    public:
       // Constructor with no arguments
       Area(): length(5), breadth(2) { }

       // Constructor with two arguments
       Area(int l, int b): length(l), breadth(b){ }

       void GetLength()
       {
           cout << "Enter length and breadth respectively: ";
           cin >> length >> breadth;
       }

       int AreaCalculation() {  return length * breadth;  }

       void DisplayArea(int temp)
       {
           cout << "Area: " << temp << endl;
       }
};

int main()
{
    Area A1, A2(2, 1);
    int temp;

    cout << "Default Area when no argument is passed." << endl;
    temp = A1.AreaCalculation();
    A1.DisplayArea(temp);

    cout << "Area when (2,1) is passed as argument." << endl;
    temp = A2.AreaCalculation();
    A2.DisplayArea(temp);

    return 0;
}
For object A1, no argument is passed while creating the object.
Thus, the constructor with no argument is invoked which initialises length to 5 and breadth to 2. Hence, area of the object A1 will be 10.
For object A2, 2 and 1 are passed as arguments while creating the object.
Thus, the constructor with two arguments is invoked which initialises length to l (2 in this case) and breadth to b (1 in this case). Hence, area of the object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as argument.
Area: 2

Default Copy Constructor

An object can be initialized with another object of same type. This is same as copying the contents of a class to another class.
In the above program, if you want to initialise an object A3 so that it contains same values as A2, this can be performed as:
....
int main()
{
   Area A1, A2(2, 1);

   // Copies the content of A2 to A3
   Area A3(A2);
     OR, 
   Area A3 = A2;
}
You might think, you need to create a new constructor to perform this task. But, no additional constructor is needed. This is because the copy constructor is already built into all classes by default.

- October 23, 2018 No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels: CPP OBJECT AND CLASS, CPP programming

C++ Pointers to Structure

C++ Pointers to Structure

In this article, you'll find relevant examples that will help you to work with pointers to access data within a structure.



A pointer variable can be created not only for native types like (int, float, doubleetc.) but they can also be created for user defined types like structure.
If you do not know what pointers are, visit C++ pointers.
Here is how you can create pointer for structures:
#include <iostream>
using namespace std;

struct temp {
    int i;
    float f;
};

int main() {
    temp *ptr;
    return 0;
}
This program creates a pointer ptr of type structure temp.

Example: Pointers to Structure

#include <iostream>
using namespace std;

struct Distance
{
    int feet;
    float inch;
};

int main()
{
    Distance *ptr, d;

    ptr = &d;
    
    cout << "Enter feet: ";
    cin >> (*ptr).feet;
    cout << "Enter inch: ";
    cin >> (*ptr).inch;
 
    cout << "Displaying information." << endl;
    cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

    return 0;
}
Output

Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches
In this program, a pointer variable ptrand normal variable d of type structure Distance is defined.
The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d. Then, the member function of variable d is accessed using pointer.
Note: Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch is exact same cell. Similarly, (*ptr).feet and d.feet is exact same cell.
The syntax to access member function using pointer is ugly and there is alternative notation -> which is more common.
ptr->feet is same as (*ptr).feet
ptr->inch is same as (*ptr).inch

- October 23, 2018 No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels: CPP programming
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • C++ Classes and Objects
    C++ Classes and Objects In this article, you will learn to work with objects and classes in C++ programming. C++ is a multi-paradigm ...
  • C++ Default Argument
    C++ Programming Default Arguments (Parameters) In this article, you'll learn what are default arguments, how are they used and neces...
  • C++ OBJECTS & FUNCTION
    How to pass and return object from a function in C++? In this article, you will learn to pass objects to a function and return object fr...
Powered By Blogger

Search This Blog

Blog Archive

  • October 2018 (39)

Labels

  • c programming (10)
  • CPP ARAYS AND STRING (4)
  • CPP FLOW CONTROL or LOOP (6)
  • CPP FUNCTION (5)
  • CPP OBJECT AND CLASS (4)
  • CPP POINTERS (4)
  • CPP programming (29)
  • CPP STRACTURES (1)

About Me

RANJIT KUMAR SAHU
View my complete profile

Report Abuse

NAVIGATION

  • About us
  • Disclaimer
  • Privacy Policy
  • Contact us
  • Terms and conditions
Simple theme. Powered by Blogger.