HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Passing objects to functions safely and efficiently

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
efficientlyobjectspassingsafelyandfunctions

Problem

I would like to have this code reviewed. I am learning C++ from a C background. How would I improve this code to make it more C++ like? This is a simple program that I wrote, which is a stripped down version of the actual full program I'm writing.

#include 
using namespace std;

class Doge{
public:
    Doge();
    Doge(Doge&);
    ~Doge();
    int GetAge() const { return itsAge; }
    void SetAge(int age) { itsAge = age; }

private:
    int itsAge;
};

Doge::Doge(){
    cout GetAge() << endl;
}

int main(){

    cout << "Make Doge" << endl;
    Doge Scott;
    cout << "Scott is " << Scott.GetAge() << endl;
    Scott.SetAge(10);
    Function(&Scott);
    cout << endl;
    return 0;
}

Solution

It doesn't feel natural to initialize a Doge with a fixed age:

Doge::Doge(){
    cout << "Doge Constructor" << endl;
    itsAge = 5;
}


It would be more natural to make age a mandatory constructor parameter:

Doge::Doge(int itsAge): itsAge(itsAge) {
    std::cout << "Doge Constructor" << std::endl;
}


The copy constructor doesn't actually copy anything.
Either remove it, or implement copying, for example:

Doge::Doge(Doge& other){
    std::cout itsAge = other.itsAge;
}


This function is declared to return a Doge *, but it returns nothing:

Doge * Function( Doge * theDoge){
    cout GetAge() << endl;
}


This raises a compiler warning, at least with g++.

You probably implemented the destructor just to see when it gets called.
That's fine, for testing.
When you're done, just remember to remove it if it's not needed.

Code Snippets

Doge::Doge(){
    cout << "Doge Constructor" << endl;
    itsAge = 5;
}
Doge::Doge(int itsAge): itsAge(itsAge) {
    std::cout << "Doge Constructor" << std::endl;
}
Doge::Doge(Doge& other){
    std::cout << "Doge Copy Constructor" << std::endl;
    this->itsAge = other.itsAge;
}
Doge * Function( Doge * theDoge){
    cout << "In Function" << endl;
    cout << "Scott is now " << theDoge->GetAge() << endl;
}

Context

StackExchange Code Review Q#64723, answer score: 8

Revisions (0)

No revisions yet.