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 length and 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.

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.https://54a13fed44ce1b2eca3741b288514ea7.safeframe.googlesyndication.com/safeframe/1-0-37/html/container.html

This class has two data members: data1 and 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 Test class are created.

In the above class Testdata1 and data2 are 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 data1 and 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 o1 to 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 data1 of o2 are not used and contains garbage value.

C++ Enumeration

In this article, you will learn to work with enumeration (enum). Also, you will learn where enums are commonly used in C++ programming.

An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used.

enum season { spring, summer, autumn, winter };

Here, the name of the enumeration is season.

And, springsummer and winter are values of type season.

By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element during declaration (if necessary).

enum season 
{   spring = 0, 
    summer = 4, 
    autumn = 8,
    winter = 12
};

Enumerated Type Declaration

When you create an enumerated type, only blueprint for the variable is created. Here’s how you can create variables of enum type.

enum boolean { false, true };

// inside function
enum boolean check;

Here, a variable check of type enum boolean is created.

Here is another way to declare same check variable using different syntax.

enum boolean 
{ 
   false, true
} check;

Example 1: Enumeration Type

#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()
{
    week today;
    today = Wednesday;
    cout << "Day " << today+1;
    return 0;
}

Output

Day 4

Example2: Changing Default Value of Enums

#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

    seasons s;

    s = summer;
    cout << "Summer = " << s << endl;

    return 0;
}

Output

Summer = 4

Why enums are used in C++ programming?

An enum variable takes only one value out of many possible values. Example to demonstrate it,

#include <iostream>
using namespace std;

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main() 
{
    card = club;
    cout << "Size of enum variable " << sizeof(card) << " bytes.";   
    return 0;
}

Output

Size of enum variable 4 bytes.

It’s because the size of an integer is 4 bytes.;

This makes enum a good choice to work with flags.

You can accomplish the same task using C++ structures. However, working with enums gives you efficiency along with flexibility.


How to use enums for flags?

Let us take an example,

enum designFlags {
	ITALICS = 1,
	BOLD = 2,
	UNDERLINE = 4
} button;

Suppose you are designing a button for Windows application. You can set flags ITALICSBOLD and UNDERLINE to work with text.

There is a reason why all the integral constants are power of 2 in above pseudocode.

// In binary

ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100 

Since, the integral constants are power of 2, you can combine two or more flags at once without overlapping using bitwise OR | operator. This allows you to choose two or more flags at once. For example,

#include <iostream>
using namespace std;

enum designFlags {
    BOLD = 1,
    ITALICS = 2,
    UNDERLINE = 4
};

int main() 
{
    int myDesign = BOLD | UNDERLINE; 

        //    00000001
        //  | 00000100
        //  ___________
        //    00000101

    cout << myDesign;

    return 0;
}

Output

5

When the output is 5, you always know that bold and underline is used.

Also, you can add flag to your requirements.

if (myDesign & ITALICS) {
    // code for italics
}

Here, we have added italics to our design. Note, only code for italics is written inside the if statement.

You can accomplish almost anything in C++ programming without using enumerations. However, they can be pretty handy in certain situations. That’s what differentiates good programmers from great programmers.

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 (intfloatdouble etc.) 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 ptr and 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

C++ Structure and Function

In this article, you’ll find relevant examples to pass structures as an argument to a function, and use them in your program.

Structure variables can be passed to a function and returned in a similar way as normal arguments.

Passing structure to function in C++

A structure variable can be passed to a function in similar way as normal argument. Consider this example:


Example 1: C++ Structure and Function

#include <iostream>
using namespace std;

struct Person
{
    char name[50];
    int age;
    float salary;
};

void displayData(Person);   // Function declaration

int main()
{
    Person p;

    cout << "Enter Full name: ";
    cin.get(p.name, 50);
    cout << "Enter age: ";
    cin >> p.age;
    cout << "Enter salary: ";
    cin >> p.salary;

    // Function call with structure variable as an argument
    displayData(p);

    return 0;
}

void displayData(Person p)
{
    cout << "\nDisplaying Information." << endl;
    cout << "Name: " << p.name << endl;
    cout <<"Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

Output

Enter Full name: Bill Jobs
Enter age: 55
Enter salary: 34233.4

Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4

In this program, user is asked to enter the nameage and salary of a Person inside main() function.

Then, the structure variable p is to passed to a function using.

displayData(p);

The return type of displayData() is void and a single argument of type structure Person is passed.

Then the members of structure p is displayed from this function.


Example 2: Returning structure from function in C++

#include <iostream>
using namespace std;

struct Person {
    char name[50];
    int age;
    float salary;
};

Person getData(Person); 
void displayData(Person); 

int main()
{

    Person p;

    p = getData(p);   
    displayData(p);

    return 0;
}

Person getData(Person p) {

    cout << "Enter Full name: ";
    cin.get(p.name, 50);

    cout << "Enter age: ";
    cin >> p.age;

    cout << "Enter salary: ";
    cin >> p.salary;

    return p;
}

void displayData(Person p)
{
    cout << "\nDisplaying Information." << endl;
    cout << "Name: " << p.name << endl;
    cout <<"Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

The output of this program is same as program above.

In this program, the structure variable p of type structure Person is defined under main() function.

The structure variable p is passed to getData() function which takes input from user which is then returned to main function.

p = getData(p); 

Note: The value of all members of a structure variable can be assigned to another structure using assignment operator = if both structure variables are of same type. You don’t need to manually assign each members.

Then the structure variable p is passed to displayData() function, which displays the information.

C++ Structures

In this article, you’ll learn about structures in C++ programming; what is it, how to define it and use it in your program.

Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collecion of data of different data types.

For example: You want to store some information about a person: his/her name, citizenship number and salary. You can easily create different variables name, citNo, salary to store these information separately.

However, in the future, you would want to store information about multiple persons. Now, you’d need to create different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no relation between the variables (information) would exist, it’s going to be a daunting task.

A better approach will be to have a collection of all related information under a single name Person, and use it for every person. Now, the code looks much cleaner, readable and efficient as well.

This collection of all related information under a single name Person is a structure.


How to declare a structure in C++ programming?

The struct keyword defines a structure type followed by an identifier (name of the structure).

Then inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that structure. For example:

struct Person
{
    char name[50];
    int age;
    float salary;
};

Here a structure person is defined which has three members: nameage and salary.

When a structure is created, no memory is allocated.

The structure definition is only the blueprint for the creating of variables. You can imagine it as a datatype. When you define an integer as below:

int foo;

The int specifies that, variable foo can hold integer element only. Similarly, structure definition only specifies that, what property a structure variable holds when it is defined.

Note: Remember to end the declaration with a semicolon (;)


How to define a structure variable?

Once you declare a structure person as above. You can define a structure variable as:

Person bill;

Here, a structure variable bill is defined which is of type structure Person.

When structure variable is defined, only then the required memory is allocated by the compiler.

Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes, memory of int is 4 bytes and memory of char is 1 byte.

Hence, 58 bytes of memory is allocated for structure variable bill.


How to access members of a structure?

The members of structure variable is accessed using a dot (.) operator.

Suppose, you want to access age of structure variable bill and assign it 50 to it. You can perform this task by using following code below:

bill.age = 50;

Example: C++ Structure

C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct Person
{
    char name[50];
    int age;
    float salary;
};

int main()
{
    Person p1;
    
    cout << "Enter Full name: ";
    cin.get(p1.name, 50);
    cout << "Enter age: ";
    cin >> p1.age;
    cout << "Enter salary: ";
    cin >> p1.salary;

    cout << "\nDisplaying Information." << endl;
    cout << "Name: " << p1.name << endl;
    cout <<"Age: " << p1.age << endl;
    cout << "Salary: " << p1.salary;

    return 0;
}

Output

Enter Full name: Magdalena Dankova
Enter age: 27
Enter salary: 1024.4

Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4

Here a structure Person is declared which has three members nameage and salary.

Inside main() function, a structure variable p1 is defined. Then, the user is asked to enter information and data entered by user is displayed.

C++ Strings

In this article, you’ll learn to handle strings in C. You’ll learn to declare them, initialize them and use them for various input/output operations.

String is a collection of characters. There are two types of strings commonly used in C++ programming language:

  • Strings that are objects of string class (The Standard C++ Library string class)
  • C-strings (C-style Strings)

C-strings

In C programming, the collection of characters is stored in the form of arrays, this is also supported in C++ programming. Hence it’s called C-strings.

C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).


How to define a C-string?

char str[] = "C++";

In the above code, str is a string and it holds 4 characters.

Although, “C++” has 3 character, the null character \0 is added to the end of the string automatically.


Alternative ways of defining a string

char str[4] = "C++";
     
char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String to read a word

C++ program to display a string entered by user.

#include <iostream>
using namespace std;

int main()
{
    char str[100];

    cout << "Enter a string: ";
    cin >> str;
    cout << "You entered: " << str << endl;

    cout << "\nEnter another string: ";
    cin >> str;
    cout << "You entered: "<<str<<endl;

    return 0;
}

Output

Enter a string: C++
You entered: C++

Enter another string: Programming is fun.
You entered: Programming

Notice that, in the second example only “Programming” is displayed instead of “Programming is fun”.

This is because the extraction operator >> works as scanf() in C and considers a space ” ” has a terminating character.


Example 2: C++ String to read a line of text

C++ program to read and display an entire line entered by user.

#include <iostream>
using namespace std;

int main()
{
    char str[100];
    cout << "Enter a string: ";
    cin.get(str, 100);

    cout << "You entered: " << str << endl;
    return 0;
}

Output

Enter a string: Programming is fun.
You entered: Programming is fun.

To read the text containing blank space, cin.get function can be used. This function takes two arguments.

First argument is the name of the string (address of first element of string) and second argument is the maximum size of the array.

In the above program, str is the name of the string and 100 is the maximum size of the array.


string Object

In C++, you can also create a string object for holding strings.

Unlike using char arrays, string objects has no fixed length, and can be extended as per your requirement.


Example 3: C++ string using string data type

#include <iostream>
using namespace std;

int main()
{
    // Declaring a string object
    string str;
    cout << "Enter a string: ";
    getline(cin, str);

    cout << "You entered: " << str << endl;
    return 0;
}

Output

Enter a string: Programming is fun.
You entered: Programming is fun.

In this program, a string str is declared. Then the string is asked from the user.

Instead of using cin>> or cin.get() function, you can get the entered line of text using getline().

getline() function takes the input stream as the first parameter which is cin and str as the location of the line to be stored.


Passing String to a Function

Strings are passed to a function in a similar way arrays are passed to a function.

#include <iostream>

using namespace std;

void display(char *);
void display(string);

int main()
{
    string str1;
    char str[100];

    cout << "Enter a string: ";
    getline(cin, str1);

    cout << "Enter another string: ";
    cin.get(str, 100, '\n');

    display(str1);
    display(str);
    return 0;
}

void display(char s[])
{
    cout << "Entered char array is: " << s << endl;
}

void display(string s)
{
    cout << "Entered string is: " << s << endl;
}

Output

Enter a string:  Programming is fun.
Enter another string:  Really?
Entered string is: Programming is fun.
Entered char array is: Really?

In the above program, two strings are asked to enter. These are stored in str and str1 respectively, where str is a char array and str1 is a string object.

Then, we have two functions display() that outputs the string onto the string.

The only difference between the two functions is the parameter. The first display() function takes char array as a parameter, while the second takes string as a parameter.

This process is known as function overloading. Learn more about Function Overloading.

Passing Array to a Function in C++ Programming

In this tutorial, we will learn how to pass a single-dimensional and multidimensional array as a function parameter in C++ with the help of examples.

In C++, we can pass arrays as an argument to a function. And, also we can return arrays from a function.

Before you learn about passing arrays as a function argument, make sure you know about Java Arrays and Java Function.


Syntax for Passing Arrays as Function Parameters

The syntax for passing an array to a function is:

returnType functionName(dataType arrayName[arraySize]) {
    // code
}

Let’s see an example,

int total(int marks[5]) {
    // code
}

Here, we have passed an int type array named marks to the function total(). The size of the array is 5.


Example 1: Passing One-dimensional Array to a Function

// C++ Program to display marks of 5 students

#include <iostream>
using namespace std;

// declare function to display marks
// take a 1d array as parameter
void display(int m[5]) {
    cout << "Displaying marks: " << endl;

    // display array elements    
    for (int i = 0; i < 5; ++i) {
        cout << "Student " << i + 1 << ": " << m[i] << endl;
    }
}

int main() {

    // declare and initialize an array
    int marks[5] = {88, 76, 90, 61, 69};
    
    // call display function
    // pass array as argument
    display(marks);

    return 0;
}

Output

Displaying marks: 
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69

Here,

  1. When we call a function by passing an array as the argument, only the name of the array is used.display(marks);Here, the argument marks represent the memory address of the first element of array marks[5].
  2. However, notice the parameter of the display() function.void display(int m[5])Here, we use the full declaration of the array in the function parameter, including the square braces [].
  3. The function parameter int m[5] converts to int* m;. This points to the same address pointed by the array marks. This means that when we manipulate m[5] in the function body, we are actually manipulating the original array marks.

    C++ handles passing an array to a function in this way to save memory and time.

Passing Multidimensional Array to a Function

We can also pass Multidimensional arrays as an argument to the function. For example,

Example 2: Passing Multidimensional Array to a Function

// C++ Program to display the elements of two
// dimensional array by passing it to a function

#include <iostream>
using namespace std;

// define a function 
// pass a 2d array as a parameter
void display(int n[][2]) {
    cout << "Displaying Values: " << endl;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 2; ++j) {
            cout << "num[" << i << "][" << j << "]: " << n[i][j] << endl;
        }
    }
}

int main() {

    // initialize 2d array
    int num[3][2] = {
        {3, 4},
        {9, 5},
        {7, 1}
    };

    // call the function
    // pass a 2d array as an argument
    display(num);

    return 0;
}

Output

Displaying Values: 
num[0][0]: 3
num[0][1]: 4
num[1][0]: 9
num[1][1]: 5
num[2][0]: 7
num[2][1]: 1

In the above program, we have defined a function named display(). The function takes a two dimensional array, int n[][2] as its argument and prints the elements of the array.

While calling the function, we only pass the name of the two dimensional array as the function argument display(num).

Note: It is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified. This is why we have used int n[][2].

We can also pass arrays with more than 2 dimensions as a function argument.


C++ Returning an Array From a Function

We can also return an array from the function. However, the actual array is not returned. Instead the address of the first element of the array is returned with the help of pointers.

We will learn about returning arrays from a function in the coming tutorials.

C++ Multidimensional Arrays

In this tutorial, we’ll learn about multi-dimensional arrays in C++. More specifically, how to declare them, access them, and use them efficiently in our program.

In C++, we can create an array of an array, known as a multidimensional array. For example:

int x[3][4];

Here, x is a two dimensional array. It can hold a maximum of 12 elements.

We can think of this array as a table with 3 rows and each row has 4 columns as shown below.

C++ two dimensional array
Elements in two dimensional array in C++ Programming

Three-dimensional arrays also work in a similar way. For example:

float x[2][4][3];

This array x can hold a maximum of 24 elements.

We can find out the total number of elements in the array simply by multiplying its dimensions:

2 x 4 x 3 = 24

Multidimensional Array Initialization

Like a normal array, we can initialize a multidimensional array in more than one way.

1. Initialization of two dimensional array

int test[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to initialize this array with the same array elements is given below:

int  test[2][3] = { {2, 4, 5}, {9, 0, 19}};

This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements each.

C++ Two-dimensional array initialization
Initializing a two-dimensional array in C++

2. Initialization of three dimensional array

int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23, 
                 2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

This is not a good way of initializing a three-dimensional array. A better way to initialise this array is:

int test[2][3][4] = { 
                     { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
                     { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
                 };

Example 1: Two Dimensional Array

// C++ Program to display all elements
// of an initialised two dimensional array

#include <iostream>
using namespace std;

int main() {
    int test[3][2] = {{2, -5},
                      {4, 0},
                      {9, 1}};

    // use of nested for loop
    // access rows of the array
    for (int i = 0; i < 3; ++i) {

        // access columns of the array
        for (int j = 0; j < 2; ++j) {
            cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
        }
    }

    return 0;
}

Run Code

Output

test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

In the above example, we have initialized a two-dimensional int array named test that has 3 “rows” and 2 “columns”.

Here, we have used the nested for loop to display the array elements.

  • the outer loop from i = 0 to i = 2 access the rows of the array
  • the inner loop from j = 0 to j = 1 access the columns of the array

https://73bfb0ad0372cb42f3f30c0252720129.safeframe.googlesyndication.com/safeframe/1-0-37/html/container.html

Finally, we print the array elements in each iteration.


Example 2: Taking Input for Two Dimensional Array

#include <iostream>
using namespace std;

int main() {
    int numbers[2][3];

    cout << "Enter 6 numbers: " << endl;

    // Storing user input in the array
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            cin >> numbers[i][j];
        }
    }

    cout << "The numbers are: " << endl;

    //  Printing array elements
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
        }
    }

    return 0;
}

Run Code

Output

Enter 6 numbers: 
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6

Here, we have used a nested for loop to take the input of the 2d array. Once all the input has been taken, we have used another nested for loop to print the array members.


Example 3: Three Dimensional Array

// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include <iostream>
using namespace std;

int main() {
    // This array can store upto 12 elements (2x3x2)
    int test[2][3][2] = {
                            {
                                {1, 2},
                                {3, 4},
                                {5, 6}
                            }, 
                            {
                                {7, 8}, 
                                {9, 10}, 
                                {11, 12}
                            }
                        };

    // Displaying the values with proper index.
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 2; ++k) {
                cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
            }
        }
    }

    return 0;
}

Run Code

Output

test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

The basic concept of printing elements of a 3d array is similar to that of a 2d array.

However, since we are manipulating 3 dimensions, we use a nested for loop with 3 total loops instead of just 2.

As we can see, the complexity of the array increases exponentially with the increase in dimensions.

C++ Arrays

In this tutorial, we will learn to work with arrays. We will learn to declare, initialize, and access array elements in C++ programming with the help of examples.

In C++, an array is a variable that can store multiple values of the same type. For example,

Suppose a class has 27 students, and we need to store the grades of all of them. Instead of creating 27 separate variables, we can simply create an array:

double grade[27];

Here, grade is an array that can hold a maximum of 27 elements of double type.

In C++, the size and type of arrays cannot be changed after its declaration.


C++ Array Declaration

dataType arrayName[arraySize];

For example,

int x[6];

Here,

  • int – type of element to be stored
  • x – name of the array
  • 6 – size of the array

Access Elements in C++ Array

In C++, each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices.

// syntax to access array elements
array[index];

Consider the array x we have seen above.

C++ Array Declaration
Elements of an array in C++

Few Things to Remember:

  • The array indices start with 0. Meaning x[0] is the first element stored at index 0.
  • If the size of an array is n, the last element is stored at index (n-1). In this example, x[5] is the last element.
  • Elements of an array have consecutive addresses. For example, suppose the starting address of x[0] is 2120d. Then, the address of the next element x[1] will be 2124d, the address of x[2] will be 2128d and so on.

    Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.

C++ Array Initialization

In C++, it’s possible to initialize an array during declaration. For example,

// declare and initialize and array
int x[6] = {19, 10, 8, 17, 9, 15};
C++ Array Initialization
C++ Array elements and their data

Another method to initialize array during declaration:

// declare and initialize an array
int x[] = {19, 10, 8, 17, 9, 15};

Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size.


C++ Array With Empty Members

In C++, if an array has a size n, we can store upto n number of elements in the array. However, what will happen if we store less than n number of elements.

For example,

// store only 3 elements in the array
int x[6] = {19, 10, 8};

Here, the array x has a size of 6. However, we have initialized it with only 3 elements.

In such cases, the compiler assigns random values to the remaining places. Oftentimes, this random value is simply 0.

C++ Array with empty members
Empty array members are automatically assigned the value 0

How to insert and print array elements?

int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9
mark[3] = 9;

// take input from the user
// store the value at third position
cin >> mark[2];


// take input from the user
// insert at ith position
cin >> mark[i-1];

// print first element of the array
cout << mark[0];

// print ith element of the array
cout >> mark[i-1];

Example 1: Displaying Array Elements

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {7, 5, 6, 12, 35};

    cout << "The numbers are: ";

    //  Printing array elements
    // using range based for loop
    for (const int &n : numbers) {
        cout << n << "  ";
    }


    cout << "\nThe numbers are: ";

    //  Printing array elements
    // using traditional for loop
    for (int i = 0; i < 5; ++i) {
        cout << numbers[i] << "  ";
    }

    return 0;
}

Run Code

Output

The numbers are: 7  5  6  12  35
The numbers are: 7  5  6  12  35

Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have printed numbers[i].

We again used a range based for loop to print out the elements of the array. To learn more about this loop, check C++ Ranged for Loop.

Note: In our range based loop, we have used the code const int &n instead of int n as the range declaration. However, the const int &n is more preferred because:

  1. Using int n simply copies the array elements to the variable n during each iteration. This is not memory-efficient.

    &n, however, uses the memory address of the array elements to access their data without copying them to a new variable. This is memory-efficient.
  2. We are simply printing the array elements, not modifying them. Therefore, we use const so as not to accidentally change the values of the array.

Example 2: Take Inputs from User and Store Them in an Array

#include <iostream>
using namespace std;

int main() {
    int numbers[5];

    cout << "Enter 5 numbers: " << endl;

    //  store input from user to array
    for (int i = 0; i < 5; ++i) {
        cin >> numbers[i];
    }

    cout << "The numbers are: ";

    //  print array elements
    for (int n = 0; n < 5; ++n) {
        cout << numbers[n] << "  ";
    }

    return 0;
}

Output

Enter 5 numbers: 
11
12
13
14
15
The numbers are: 11  12  13  14  15

Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an input from the user and stored it in numbers[i].

Then, we used another for loop to print all the array elements.


Example 3: Display Sum and Average of Array Elements Using for Loop

#include <iostream>
using namespace std;

int main() {
    
    // initialize an array without specifying size
    double numbers[] = {7, 5, 6, 12, 35, 27};

    double sum = 0;
    double count = 0;
    double average;

    cout << "The numbers are: ";

    //  print array elements
    // use of range-based for loop
    for (const double &n : numbers) {
        cout << n << "  ";

        //  calculate the sum
        sum += n;

        // count the no. of array elements
        ++count;
    }

    // print the sum
    cout << "\nTheir Sum = " << sum << endl;

    // find the average
    average = sum / count;
    cout << "Their Average = " << average << endl;

    return 0;
}

Output

The numbers are: 7  5  6  12  35  27
Their Sum = 92
Their Average = 15.3333

In this program:

  1. We have initialized a double array named numbers but without specifying its size. We also declared three double variables sumcount, and average.

    Here, sum =0 and count = 0.
  2. Then we used a range based for loop to print the array elements. In each iteration of the loop, we add the current array element to sum.
  3. We also increase the value of count by 1 in each iteration, so that we can get the size of the array by the end of the for loop.
  4. After printing all the elements, we print the sum and the average of all the numbers. The average of the numbers is given by average = sum / count;

Note: We used a ranged for loop instead of a normal for loop.

A normal for loop requires us to specify the number of iterations, which is given by the size of the array.

But a ranged for loop does not require such specifications.