Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should accessors be Inlined?

Tags:

c++

inline

This is the declaration in the header file:

class PrimeSieve  
{
    populate(int lim);
    vector<int> sieve;
    long long limit;

    public:
        unsigned int limit();
};

Should I define the accessor method in the .cpp file or in the .h, inline?

I'm new to C++, but I'd like to follow best practices. I've seen this around in some of the books—is this considered standard?

unsigned int limit() { return limit; };
like image 535
Roy Avatar asked Dec 19 '11 03:12

Roy


People also ask

What is the point of accessors?

In computer programming, an accessor method is a method that fetches private data that is stored within an object. An accessor provides the means by which to obtain the state of an object from other program parts.

Are constructors Inlined?

Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile .

Which of the following is a characteristic of an accessor?

Accessor Function They are used instead of making a class member variable public and changing it directly within an object. To access a private object member, an accessor function must be called. Typically for a member such as Level, a function GetLevel() returns the value of Level and SetLevel() to assign it a value.

What is the difference between an accessor and a mutator method for a class?

An accessor is a class method used to read data members, while a mutator is a class method used to change data members. It's best practice to make data members private (as in the example above) and only access them via accessors and mutators.


2 Answers

Definitely write the accessor inline in the header file. It makes better optimizations possible, and doesn't reduce encapsulation (since changes to the format of private data require recompiling all units that include the header anyway).

In the case of a complicated algorithm, you might want to hide the definition in an implementation file. Or when the implementation requires some types/header files not otherwise required by the class definition. Neither of those cases applies to simple accessors.

For one-liners, put it inside the class definition. Slightly longer member functions should still be in the header file, but might be declared explicitly inline, following the class definition.

like image 143
Ben Voigt Avatar answered Nov 03 '22 03:11

Ben Voigt


Most newer compilers are smart enough to inline what is necessary and leave everything else alone. So let the compiler do what its good at and don't try to second guess it.

Put all your code in the .cpp and the code declarations in the .h.

like image 31
Gregor Brandt Avatar answered Nov 03 '22 04:11

Gregor Brandt