Reputation: 162
This is the code.
#include<iostream>
using namespace std;
class Item{
double itemPrice;
int qty;
public:
Item(){
cout<<"Enter Item Price : "<<endl;
cin>>itemPrice;
cout<<"Enter QTY : " <<endl;
cin>>qty;
}
double getItemTotal(){
return itemPrice*qty;
}
};
class Order{
int index;
int orderId;
double orderValue;
Item items[20];
public:
Order(){
index=0;
cout<<"\nEnter Order ID : ";
cin>>orderId;
}
void viewOrderDetails(){
for(int j=0;j<20;j++){
Item ii=items[j];
orderValue=orderValue+ii.getItemTotal();
}
cout<<"Order ID : "<<orderId<<endl;
cout<<"Order Value : "<<orderValue<<endl;
}
void addToOrder(Item i){
if(index<19){
items[index]=i;
index=index+1;
}else{
cout<<"\nOrder Full";
}
}
};
int main(){
Order odr1;
Item i1;
Item i2;
odr1.addToOrder(i1);
odr1.addToOrder(i2);
odr1.viewOrderDetails();
return 0;
}
I want to run the constructor of Order class. But it runs the Constructor of Item class. I checked the code many times and did a research.But I cant seem any wrong in the code. I am using CodeBlocks IDE with GCC Compiler( MingGW ). I appreciate if anybody can help me with this. Thanks.
Upvotes: 0
Views: 234
Reputation: 448
The constructor of your Order class will get callled.
Item items[20]; // <-- here you actually create 20 Items and the constructor for each Item will be called. Then the Order Constructor will get called.
You could use std::list<Item> items;
instead of Item items[20]
. In that case you don't actually create an Item (and therefore its constructor will not get called) you just create a container where you can store your items.
Anyway, it is bad practice to do what you do in your constructor. A constructor should initialize the object and it should run fast. So create a method instead.
Upvotes: 1
Reputation: 118425
Your Order class is:
class Order{
int index;
int orderId;
double orderValue;
Item items[20];
public:
Order(){
// the body of the constructor
Your Order
class contains an array of 20 Item
s.
Before the code in the constructor executes, all class members have to be constructed, first.
Since your Order
class contains 20 Item
s, each one of them must be constructed first, and Item
's default constructor is going to get called twenty times, before the body of the Order
's constructor starts executing. This is how C++ works.
This is the explanation for why you're seeing the code in Item
's default constructor getting apparently executed before the code in Order
's default constructor.
Instead of:
Item items[20];
you need to use a vector:
std::vector<Item> items;
and have addToOrder()
use push_back()
to initialize the vector.
Upvotes: 0