Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Style Convention: Parameter Names within Class Declaration

I'm a fairly new C++ programmer and I would like to hear the arguments for and against naming parameters within the class declaration.


Here's an example:

Student.h

#ifndef STUDENT_H_
#define STUDENT_H_

#include <string>

using namespace std;

class Student
{
    private:
        string name;
        unsigned int age;
        float height, GPA;

    public:
        Student(string, unsigned int, float, float);

        void setAge(unsigned int);
};

#endif /*STUDENT_H_*/

vs.

#ifndef STUDENT_H_
#define STUDENT_H_

#include <string>

class Student
{
    private:
        string name;
        unsigned int age;
        float height, GPA;

    public:
        Student(string name, unsigned int age, float height, float GPA);

        void setAge(unsigned int age);
};

#endif /*STUDENT_H_*/

Student.cpp

#include "Student.h"

Student::Student(   string name,
            unsigned int age,
            float height,
            float GPA) :

            name(name),
            age(age),
            height(height),
            GPA(GPA) {}

void Student::setAge(unsigned int age) { this -> age = age; }

I cannot decide. On the one hand, I feel that it is redundant to name the variables in both the declaration (.h) and the definition (.cpp). Especially since you have to worry about updating the names in both places so that they match. On the other hand, without names, it can often be confusing to determine what variables the parameters correspond to just by looking at the declaration.

So, what are your thoughts?

like image 717
Scott Avatar asked Apr 21 '09 07:04

Scott


2 Answers

It is much better to use the parameter names in the declaration, and use good parameter names. This way, they serve as function documentation. Otherwise, you will have to write additional comments in your header, and it is always better to use good parameter/variable names than to use comments.

Exception: when a function must have a certain signature for external reasons, but the parameters are not actually used. In this case, you should not name them in the implementation either.

like image 182
Gorpik Avatar answered Sep 27 '22 21:09

Gorpik


Put the names in both places, clarity is the reward you get for the task of maintaining the signatures in two places.

like image 38
Binary Worrier Avatar answered Sep 27 '22 23:09

Binary Worrier