Username
Username

Reputation: 3663

Looping thru member array gives wrong values

I've set up two classes, Dog and AnotherDog. Dog is not meant to be a base class for AnotherDog.

In AnotherDog, I have a Dog object. Within that Dog object is a member array. When an AnotherDog object call its Dog member, then has the member loop thru its member array, I get the wrong results.

#include <iostream>

class Dog
{
private:
    int m_NumberOfBarks;
    int m_Decibels[];
public:
    Dog();
    ~Dog();

    void setBarkDecibels(int decibel1, int decibel2);
    void loopDecibels();
};

Dog::Dog() : m_NumberOfBarks(2){}
Dog::~Dog(){}

void Dog::setBarkDecibels(int decibel1, int decibel2){
    m_Decibels[0]=  decibel1;
    m_Decibels[1]=  decibel2;
}

void Dog::loopDecibels(){
    for(int i=0; i<m_NumberOfBarks; ++i){
        std::cout << i << ' ' << m_Decibels[i] << std::endl;
    }
}


class AnotherDog
{
private:
    Dog m_Dog;
public:
    AnotherDog();
    ~AnotherDog();

    Dog getDog();
};

AnotherDog::AnotherDog(){
    m_Dog.setBarkDecibels(10, 100);
}
AnotherDog::~AnotherDog(){}

Dog AnotherDog::getDog(){
    return m_Dog;
}


int main(){
    AnotherDog goodDog;
    goodDog.getDog().loopDecibels();
    return 0;
}

I want void Dog::loopDecibels() to print 10 and 100, along with the index.

Instead I get this:

0 0
1 4196480

What am I doing wrong?

How do I achieve the result I want?

Upvotes: 0

Views: 107

Answers (1)

SergeyA
SergeyA

Reputation: 62563

Your program exhibits undefined behaviour.

 int m_Decibels[];

Declares a pointer to int, and does not allocate any memory for the pointer to point to. Pointer remains uninitialized in the class constructor (since you do not initialize it). When later you do

m_Decibels[0]=  decibel1;
m_Decibels[1]=  decibel2;

You are dereferencing this pointer, which is a no-no. To fix this, you can use a fixed-size array:

int m_Decibels[2];

The other side of the coin is that you are returning an instance of Dog from your getDog by value. When you are setting your decibels on this particular instance, it has no effect on the original dog member of the class. To fix this, you might want to return your object by a reference, like this:

   Dog& getDog(); // and corresponding change in the definition

Upvotes: 4

Related Questions