×

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

Array of objects with parameterized constructors in C++ with Example

Learn: How to declare an array of objects in C++ programming language with parameterized constructors? Initialize of data members while creating array of objects in C++.

Last posts on constructors (if you did not read them, I would recommend reading them first), here are the covered topics:

In this post, we will learn how to initialize data members while creating an array of objects using parameterized constructors in C++ programming language?

Array of objects with parameterized constructors in C++

As we have discussed in last post that parameterized constructor enables argument (parameter) passing to initialize data members while creating the class. We can also initialize the data members of an array of objects using the parameterized constructors. It is really very simple like array initialization:

Declaration of array of objects

Consider the given declaration of array of objects:

Let suppose there is a class named Demo, with three data members of integer type A, B and C, and parameterized constrictor exists in the class, we can initialize the data members like this:

Demo obj[2] = {{1,2,3},{11,12,13}};

Here, obj[0] will be initialized with 1,2,3 and obj[1] will be initialized with 11, 12 13.

Example of array of objects with parameterized constructors

Consider the given program:

#include <iostream>
using namespace std;

class Demo {
 private:
  int A;
  int B;
  int C;

 public:
  // parameterized constructor
  Demo(int A, int B, int C);
  void set(int A, int B, int C);
  void print();
};

Demo::Demo(int A, int B, int C) {
  this->A = A;
  this->B = B;
  this->C = C;
}

void Demo::set(int A, int B, int C) {
  this->A = A;
  this->B = B;
  this->C = C;
}

void Demo::print() {
  cout << "Value of A :  " << A << endl;
  cout << "Value of B :  " << B << endl;
  cout << "Value of C :  " << C << endl;
}

int main() {
  // Calling of parameterized constructor with array of object.
  Demo obj[2] = {{1, 2, 3}, {11, 12, 13}};

  // print values
  obj[0].print();
  obj[1].print();

  // set new values
  obj[0].set(100, 200, 300);
  obj[1].set(1000, 2000, 3000);

  // print values
  obj[0].print();
  obj[1].print();

  return 0;
}

Output

Value of A :  1
Value of B :  2
Value of C :  3
Value of A :  11
Value of B :  12
Value of C :  13
Value of A :  100
Value of B :  200
Value of C :  300
Value of A :  1000
Value of B :  2000
Value of C :  3000

Comments and Discussions!

Load comments ↻





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