Click here to Skip to main content
15,887,999 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How does this statement is able to run successfully
C++
obj = b[0];
cout<<obj.a<<"   "<<obj.b<<"\n";
obj = b[1];
cout<<obj.a<<"   "<<obj.b<<"\n";

//code

Thanks in advance

C++
#include<vector>
#include<iostream>
#include"conio.h"
using namespace std;
class B{
public:
	int a ;
	int b;
public:
	B(){}
	B(int c,int d):a(c),b(d){cout<<"contructor\n";}
	~B(){cout<<"destructor\n";}
};

int main()
{
std::vector<B> b;
B obj;
b.push_back(B(10,20));
b.push_back(B(30,40));
obj = b[0];
cout<<obj.a<<"   "<<obj.b<<"\n";
obj = b[1];
cout<<obj.a<<"   "<<obj.b<<"\n";
getch();
}


Output:
contructor
destructor
contructor
destructor
destructor
10   20
30   40
Posted
Updated 18-Jul-15 4:08am
v6
Comments
PIEBALDconsult 17-Jul-15 14:08pm    
Because it C/C++ and someday you may find that you have blown your leg off.
nv3 17-Jul-15 17:36pm    
The line "std::vector b;" tells me that you are not showing us the exact code of your example. 'b' is not a type. Hence that statement would not compile. I assume you meant to write: "std::vector b;".

And what is so unusual about the output? Can you elaborate a little more what you actual question is.
[no name] 17-Jul-15 20:52pm    
Not a question yet.

1 solution

Your interpretation is wrong. Calling push_back() makes a copy of the stack object to insert in the vector.
This creates an object with automatic storage duration:
C++
b.push_back(B(10,20));

which immediately goes out of scope. The destructor is called on the stack object but a new copy exists in the vector.
http://www.cplusplus.com/reference/vector/vector/[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900