namu
namu

Reputation: 146

constructor called in main, but object not created properly

I am trying to call the constructor H, but for some reason its not being called. I get no error when I compile my code, and I get the output:

A object initialized.

H object initialized.

If H was initialized properly, the cout from the constructor should also be shown.

Can someone please help? Thank you.

I also have another question. How can I change the value of hVec[i].a and have the value of aArray[i].a take upon this value as well? I know I am suppose to use pointers, but an very confused. Sorry for all the questions; I'm reltaively new to programming in C++.

#include <vector>
#include <iostream>

struct A
{
  A(int av):a(av){}
     
    int a;
};

struct Heap
{
  
  Heap(std::vector<A> hVal)
  {
      std::cout << "Constructor for H object. \n";
      for (int i=0; i<hVal.size(); ++i) 
      {
          hVec.push_back(hVal[i]);
          std::cout << "hVec[i].a = " << hVec[i].a << "   ";
      }
      std::cout << std::endl;
  }
  
  std::vector<A> hVec;
};


int main()
{
  A a0(2), a1(4), a2(8);  
  std::vector<A> aArray;  
  aArray.push_back(a0);
  aArray.push_back(a1);
  aArray.push_back(a2);         
  std::cout << "A object initialized. \n";

  Heap h(A);

  std::cout << "H object initialized. \n";
  
  return 0;

}

Upvotes: 0

Views: 120

Answers (3)

billz
billz

Reputation: 45420

Your struct Heap does not have a constructor which takes A as argument.

However, you can initialize h with aArray which is std::vector<A> type

Heap h(aArray);

In C++, unless you are trying to be compatible with C, otherwise just use class instead of struct

Upvotes: 2

fefe
fefe

Reputation: 3442

use Heap h(aArray); instead of Heap h(A);

The line Heap h(A); declares a function h taking an object of type A as parameter, and returns an object Heap.

Upvotes: 0

James McNellis
James McNellis

Reputation: 355107

Heap h(A);

This declares a function of type Heap(A) named h. Perhaps you meant:

Heap h(aArray);

This declares a local variable of type Heap named h.

Upvotes: 2

Related Questions