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;
}
Your
struct Heapdoes not have a constructor which takesAas argument.However, you can initialize h with aArray which is
std::vector<A>typeIn C++, unless you are trying to be compatible with C, otherwise just use
classinstead ofstruct