Most of the book examples I've seen re initializing array of class objects have been 'by hand', e.g.
Code:
Dog dogs[2] = {Dog("Frisky", 2), Dog("Tabby", 3);
where the data members are names and ages of the dogs for example, etc.
I'm trying to initialize an array of similar class objects by looping the default constructor through the array but getting weird results. Though my array takes only 3 elements, the code is not reading the first 3 inputs but if I keep adding data it saves the 4th, 5th and 6th entries and prints them out. Any helps re where I'm going wrong would be much appreciated. Thanks
Code:
#include<iostream>using namespace std;
const int MEMB = 3;
class Dog{
private:
string m_name;
int m_age;
public:
Dog(){
cout<<"Enter dog's name: ";
string name;
cin>>name;
m_name = name;
cout<<"Enter dog's age: ";
int age;
cin>>age;
m_age = age;
}
void showDog(){
cout<<"The dog's name is: "<<m_name<<endl;
cout<<"The dog's age is: "<<m_age<<" years"<<endl;
}
};
int main(){
Dog list[MEMB];
for (int i = 0; i < MEMB; i++){
list[i]=Dog();
cout<<endl;
}
cout<<endl;
for (int i = 0; i < MEMB; i++){
list[i].showDog();
cout<<endl;
}
}