×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Initialization of Array of Objects in C++

We can initialize array of objects with the help of constructors, especially parameterized constructor. Parameterized constructor passes the given value (while declaration of the object) to the variables associated to the object.

Example of Initialization of Array of Objects

Let's consider the following example/program

#include <iostream>
using namespace std;

class Number {
 private:
  int a;
  float b;

 public:
  // default constructor
  Number() {
    a = 0;
    b = 0.0f;
  }
  // Parameterized constructor
  Number(int x, float y) {
    a = x;
    b = y;
  }
  // print function
  void printValue() { cout << "a=" << a << ",b=" << b << endl; }
};

int main() {
  Number NUM[3] = {Number(10, 20.00f), Number(15, 30.56f), Number(20, 45.50f)};
  
  NUM[0].printValue();
  NUM[1].printValue();
  NUM[2].printValue();

  return 0;
}

Output

a=10,b=20 
a=15,b=30.56
a=20,b=45.5

Explanation

In this program, Number is a class and NUM is the array of objects.

While creating the array of objects, we are passing the constructor with values as array arguments and the variables a, b will be initialized with the corresponding values.

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.