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; };
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.
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With