Edgars
Edgars

Reputation: 11

Getter/setter in c++ is this the right way?

I have made a small program and it works, yet I dont know if it is the right way, especially with the getter, so here are bits of my code, would be nice if you could tell if its righ or if its not, if there's a better way to define setters and getters.

#include"head.h"

int main()
{
    field f("big_field", 20 , 10);
    f.print();
    cout << "Area: " << f.getArea() << endl;
    field t=f;
    t.setPlatums(20);
    t.print();
    cout << "Area: " << t.getArea()<< endl;
    return 0;
}

well this seems ok.

#include<iostream>
using namespace std;

class field
{
    string kads;
    int garums;
    int platums;
public:
    void print();
    field(const string& , int,  int);
    int getArea();
    void setPlatums(int);
};

and now for the other stuff and getter:

#include "head.h"

field::field(const string&t, int a, int b)
{
    kads = t;
    garums = a;
    platums = b;
}

void field::print()
{
    cout << kads << " " << garums << " " << platums << endl;
}

int field::getArea()
{
    return garums*platums;
}

void field::setPlatums(int b)
{
    platums=b;
};

This might not seem like a problem because the code is working, but maybe im doing it wrong, I mean the code isn't allways right only because it is working.

Thanks for the fast responses, it's good to hear that im learining the right way, because it's hard to re-learn the wrong way.

Upvotes: 1

Views: 907

Answers (2)

Raydel Miranda
Raydel Miranda

Reputation: 14370

#include<iostream>

using namespace std;

class field
{

public:
    ...

    // You could implement getters as const functions.
    // int getArea();                
    int getArea() const;

    void setPlatums(int);   
};

Upvotes: 1

masoud
masoud

Reputation: 56549

It's OK. However you should initialize the members through initializer-list of the constructor:

field::field(const string&t, int a, int b) :  kads(t), garums(a), platums(b)
{
}

 

On the other hand, you can replace print by overriding operator << for output streams:

#include <iostream>

class field
{
   .
   .
   .
   friend std::ostream& operator<<(std::ostream& os, const field& f);
};


std::ostream& operator<<(std::ostream& os, const field& f)
{
    os << kads << " " << garums << " " << platums << std::endl;
    return os;
}

 

Another one, try not to use using namespace std; in the header file.

Finally, when you're calculating the area in the getArea then you don't need member area in the class. Unless you pre-calculate it on setters and the return area.

Upvotes: 2

Related Questions