familyGuy familyGuy - 2 months ago 6
C++ Question

Not able to return the value from a function

I am learning inheritance in C++ and trying to return value from a function "age". All I get back is 0. I have spent hours to figure out, but no luck. This is my code below. I'll greatly appreciate any help on this!

.h class

#include <stdio.h>
#include <string>
using namespace std;

class Mother
{
public:
Mother();
Mother(double h);

void setH(double h);
double getH();

//--message handler
void print();
void sayName();
double age(double a);

private:
double ag;
};


.cpp

#include <iostream>
#include <string>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;

Mother::Mother(){}

Mother::Mother(double h)
{
ag=h;

}

void setH(double h){}
double getH();

void Mother::print(){
cout<<"I am " <<ag <<endl;
}


void Mother::sayName(){
cout<<"I am Sandy" <<endl;
}

double Mother::age(double a)
{
return a;
}


main

#include <iostream>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;

int main(int argc, const char * argv[]) {
Mother mom;
mom.sayName();
mom.age(40);
mom.print();

//Daughter d;
//d.sayName();
return 0;

Answer

function age doesn't assign value a to the member ag but instead it returns the value a which it takes as parameter it's such a bad thing. to get what I want to say in main write:

cout << mom.age(40) << endl; // 40

to make it correct change you function age to:

double Mother::age(double a)
{
    ag = a;
    return a; // it's redundant to do so. change this function to return void as long as we don't need the return value
}

*** another thing you should do:

make "getters" const to prevent changing member data and only let "setters" not constant. eg in your code: class mother:

double getH()const; // instead of double getH() const prevents changing member data "ag"