cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
Beginners
classes
classes
Apr 2, 2018 at 7:49am UTC
moo2401
(7)
#include<iostream>
class A
{
public :
int*x;
};
class B
{
public:
A _a;
};
int main()
{
B b1;
b1._a.x = new int(1);
B b2(b1);
*b2._a.x = 2;
std::cout<< b2._a.x << std::endl;
std::cout<< b1._a.x << std::endl;
system("pause");
}
what does B b2(b1); mean ?
Apr 2, 2018 at 8:17am UTC
Peter87
(11238)
It means the same as
B b2 = b1;
.
b2 is created as a copy of b1.
Apr 2, 2018 at 9:14am UTC
moo2401
(7)
so when using operator () its the same as using =
that is new and thanks peter for the help
Apr 3, 2018 at 12:25pm UTC
Enoizat
(1343)
so when using operator () its the same as using =
I’m afraid that’s not accurate.
In C++ you can overload operator(), and the expression “operator()” usually refers to that procedure. But here you’re getting advantage of implicitly-defined copy constructor
http://en.cppreference.com/w/cpp/language/copy_constructor
and implicitly-defined copy assignment operator
http://en.cppreference.com/w/cpp/language/copy_assignment
Note: in your example both of them might disappoint you, since they copy the pointer, not what is pointed to. Therefore, after being copy-constructed, both “x” member of b1 and b2 point to the same memory area. You normally don’t want that.
Topic archived. No new replies allowed.