C++ array declaration and object construction

Pig * ptr = new Pig[5]; // pointer to an array of simple Pig objects
Q: Does this create 5 Pig objects? YES tested. P238[[ 24 ]]
Q: using no-arg constructor? yes tested.
Q: contiguous memory? yes

Note the return type of this or the singular-new is identical — ptr to Pig. No one knows to use array-delete except the guy initializing the ptr.

Pig arr[5];
Q: Does this create 5 empty Pig objects? … in contiguous memory? YES … on stack? ALWAYS!
Q: no-arg constructor needed? Yes.
Q: How many times does constructor get called if we use a debugger? 5 times

#include
#define SIZE 3
using namespace std;
#define S(x) cout<<#x<<":\t"<<x<<"\n";
class CAT {
public:
CAT() {
cout < no-arg constructor with addr = ” << this << "\n";
itsAge = 0;
itsWeight = 0;
} // default constructor
~CAT(); // destructor
int GetAge() const {
return itsAge;
}
int GetWeight() const {
return itsWeight;
}
void SetAge(int age) {
itsAge = age;
}
CAT operator=(const CAT&);
CAT::CAT(const CAT&);
private:
int itsAge, itsWeight;
};
CAT::CAT(const CAT& rhs) {
cout < copy constructor ” << this << " <- " << &rhs << "\n";
this->itsAge = rhs.itsAge;
this->itsWeight = 8888888;
cout << "<– copy constructor\n";
}
// if you return CAT& then you won’t call copy constructor upon return
CAT CAT::operator=(const CAT& rhs) {
cout < assigning ” << this << " <- " << &rhs << "\n";
if (this == &rhs)
return *this;
this->itsAge = rhs.itsAge;
this->itsWeight = 11111111;
cout << "<– assignment " << this << " <- " << &rhs << "\n";
return *this;
}
CAT::~CAT() {
cout << this << " Destructor called!\n";
this->itsAge = this->itsWeight = 999999999;
}
int main() {
CAT * Family = new CAT[SIZE];
cout << "<– array declaration\n";
int i;
CAT * pCat;
for (i = 0; i < SIZE; i++) {
pCat = new CAT; // same memory location would be reused after reclaim!
pCat->SetAge(2 * i + 1);
CAT & alias2family = Family[i];
CAT * tmp = &(Family[i] = *pCat);
S(tmp);// same addr across iterations, due to the assignment pbclone
delete pCat;
}
for (i = 0; i < SIZE; i++)
std::cout << "Cat #" << i + 1 << ": " << Family[i].GetAge()
<< std::endl;
delete[] Family;
//system(“pause”);
return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s