question about Scope Resolution Operator in C++? - c++

I am learning C++ and not quite sure about the Scope Resolution Operator.
suppose I have the following code:
code 1:
class Student {
int no;
int semester;
char grade[M+1];
public:
void display() const;
};
void Student::display() const {
cout << "Hi!" << endl;
}
code 2:
class Student {
int no;
int semester;
char grade[M+1];
public:
void display() const{
cout << "Hi!" << endl;
}
};
any differences if I define the display() inside its class? if there is no difference, then why should I use the scope resolution operator?

There is one difference - if defined in the class the function behaves as if it were declared as inline. But this is no big deal, and the compiler may well ignore it. The big difference is that for large, multi-file projects, if you make a change to the function body defined in the header, EVERY other file that uses your header will have to be recompiled. Whereas, if you make a change to the function body defined in a .cpp file, then only that file needs to be recompiled. This can and does make a huge difference to real-world projects.

The scope resolution operator allows you to define the function outside the class.
This provides the ability to not expose/abstract your source code implementation from the users of your library. The class declarations are placed in header files and the actual definitions are kept in a cpp file and then only the object files or libraries of the same are provided to the end user.
You can say it provides oneway of protecting intellectual rights though the feature was not designed specifically for it.

Normally you would define the class in the header file and then implement it in the .cpp file. For the compiler to know what function belongs to which class, you use the Scope Resolution Operator, ie ::.
When you place the function directly inside your header like you showed in example two, you need to prefix it with the inline keyword, which tells the compiler to put that entire function inside the code where you are calling it. Normally you do this with very small functions and for speed considerations, using it a lot can lead to code bloat in your exe.

The main reason is that you don't want to clutter up the class
definition with all sorts of irrelevant implementation details,
like the implementation of a function. When the class is small,
with only one or two functions, and the functions are small,
with only one or two lines, it's not necessarily a problem, but
in real life, putting the function definitions in the class
itself very quickly leads to unreadable code; you want to keep
the external definition separate from the internal
implementation as much as possible. (On large projects, they'll
typically be maintained by different people anyway.)

Related

C++ Declaration of class variables in header or .cpp?

So far, I've been using classes the following way:
GameEngine.h declares the class as follows
class GameEngine {
public:
// Declaration of constructor and public methods
private:
InputManager inputManager;
int a, b, c;
// Declaration of private methods
};
My GameEngine.cpp files then just implement the methods
#include "____.h"
GameEngine::GameEngine() {
}
void GameEngine::run() {
// stuff
}
However, I've recently read that variable declarations are not supposed to be in the header file. In the above example, that would be an inputManager and a, b, c.
Now, I've been searching for where to put the variable declarations, the closest answer I found was this: Variable declaration in a header file
However, I'm not sure if the use of extern would make sense here; I just declare private variables that will only be used in an instance of the class itself. Are my variable declarations in the header files fine? Or should I put them elsewhere? If I should put them in the cpp file, do they go directly under the #include?
Don't confuse a type's members with variables. A class/struct definition is merely describing what constitutes a type, without actually declaring the existence of any variables, anything to be constructed on memory, anything addressable.
In the traditional sense, modern class design practices recommend you pretend they are "black boxes": stuff goes in, they can perform certain tasks, maybe output some other info. We do this with class methods all the time, briefly describing their signature on the .h/.hpp/.hxx file and hiding the implementation details in the .cpp/.cc/.cxx file.
While the same philosophy can be applied to members, the current state of C++, how translation units are compiled individually make this way harder to implement. There's certainly nothing "out of the box" that helps you here. The basic, fundamental problem is that for almost anything to use your class, it kind of needs to know the size in bytes, and this is something constrained by the member fields and the order of declaration. Even if they're private and nothing outside the scope of the type should be able to manipulate them, they still need to briefly know what they are.
If you actually want to hide this information to outsiders, certain idioms such as PImpl and inlined PImpl can help. But I'd recommend you don't go this way unless you're actually:
Writing a library with a semi-stable ABI, even if you make tons of changes.
Need to hide non-portable, platform-specific code.
Need to reduce pre-processor times due to an abundance of includes.
Need to reduce compile times directly impacted by this exposure of information.
What the guideline is actually talking about is to never declare global variables in headers. Any translation unit that takes advantage of your header, even if indirectly, will end up declaring its own global variable as per header instructions. Everything will compile just fine when examined individually, but the linker will complain that you have more than one definition for the same thing (which is a big no-no in C++)
If you need to reserve memory / construct something and bind it to a variable's name, always try to make that happen in the source file(s).
Class member variables must be declared in the class definition, which is usually in a header file. This should be done without any extern keywords, completely normally, like you have been doing so far.
Only variables that are not class members and that need to be declared in a header file should be declared extern.
As a general rule:
Variables that are to be used with many functions in the same class go in the class declaration.
Temporary variables for individual functions go in the functions themselves.
It seems that InputManager inputManager; belongs in the class header.
int a, b, c; is harder to know from here. What are they used for? They look like temporary variables that would be better off in the function(s) they're used in, but I can't say for sure without proper context.
extern has no use here.

Where should I implement my class method?

I aware of three different kind of implementation "locations" for my class methods:
1) Define the method inside my class (.h file) and implement it in my .cpp file
//.h
class Foo
{
int getVal() const;
};
//.cpp
int Foo::getVal() const
{ return 0; }
2) Define and implement the method inside my class (.h file).
//.h
class Foo
{
int getVal() const
{ return 0; }
};
3) Define the method inside my class and implement it outside the class but inside my header file.
//.h
class Foo
{
int getVal() const;
};
int Foo::getVal() const
{ return 0; }
What are the main differences between these three approaches?
There are three elements to this question: readability (how good the code looks), compilation (how much the compiler can optimize it) and implementation hiding (If you use the code as a library, you may not want to explicitly share your special sauce with the world).
Method one exposes only the interface for the function in the header file. This means you show a nice clean interface, and your implementation is not exposed in plaintext. However, the code cannot be inlined across compilation units, so it has the potential to be a little slower in runtime (in practice, this only matters for a very, very very small percentage of the code). THIS SHOULD BE YOUR DEFAULT WAY TO GO.
Method 2 is implicit inlining. Long functions will clutter up your class which (imho) is bad. Also exposes your implementation to the world. However, the function can be inlined and is less verbose than defining it in another place. I reserve this for very small functions.
Method 3 is actually illegal, as you will break the one-definition rule, but the following is fine:
//Foo.h
class Foo {
int getVal() const;
};
inline int Foo::getVal() const {
return 0;
}
I use this when I want to keep the class definition clean but want the function definition in the header file (for inlinable or template functions).
(1) will compile faster for a large project (only have to compile the definition of getVal once in Foo.cpp, and only have to recompile one thing if definition changes), and you get a very clear interface for a class for people who want to look it up. On the other hand, you can't inline getVal().
(2) and (3) will compile slower and add way more dependencies to your definitions changing. But you can inline getVal(). Also this is required if getVal is a template function. NOTE (3) will cause linker errors if your header is included multiple times - you'll have to mark remember to label your function inline. This is a good reason to prefer (1) and (2) to (3).
Really it's not a matter of picking (1) vs (2). You will probably use both in large projects - put the definitions of the functions that should be inlined (and templates) in the header, and put the ones that inlining makes less sense for in the cpp.
A minor note before I begin, there are lots of words that are very similar used to describe these things, I will be using declaration for the portion in the header file (int getVal() const) and implementation for the portion in the cpp file (int Foo::getVal() const). Apologies if these aren't perfectly accurate.
Also note that benefits are penalties for the others, in case that isn't clear.
1) Define the method inside my class (.h file) and implement it in my .cpp file
This is considered the standard method, and generally accepted to be the default (there are numerous exceptions, so default might be a little strong).
It separates the declaration from the implementation. This provides a few benefits:
You only need to compile the implementation once. This could potentially save compilation time.
You only need the declaration to reference. This can avoid ordering issues and is vital for circular references between classes.
You don't distribute your implementation, this can be good for closed source systems as you often have to distrbute lots of your .h files for others to plug into your system.
2) Define and implement the method inside my class (.h file).
This is called an inline implementation, it should be used in simple implementations only. It has a few benefits too:
Most compilers take this as a huge inline hint. It doesn't guarantee inling but it is very likely, which for simple methods can be a win. Property style methods are a common example.
Your implementation is trivial to find as it is straight in the declaration.
3) Define the method inside my class and implement it outside the class but inside my header file.
I haven't seen this before, but would assume it is used when the definition is non-trivial but you want the inline benefits of 2. IdeaHat mentions that the inline keyword is required in this case.

Should accessors be Inlined?

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; };
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.
A good rule of thumb is to put all your code in the .cpp file, so this would argue against an inline function in the .h file.
For simple data types in classes fully visible to clients of the class, there is no real difference as you need to recompile the client whenever the class definition changes.
The main reason to make an accessor rather than use the member directly is to allow the implementation to remove the data member later on and still keep the interface compatible; if the interface containing the accessor is unchanged, the result is typically binary compatible, otherwise, it's source compatible. Having the accessor inline means defining it as part of the interface that you are changing, so you can ever only be source compatible.
The other reason to have an accessor is a DLL boundary: If your accessor needs to call into another function, and you allow it to be inlined, then this function's symbol needs to be exported to the client as well.
Depending on the complexity of the project, it can be beneficial to define an interface for your code as an abstract class, which allows you to change the implementation to your heart's content without the client ever seeing the change; in this case, accessors are defined as abstract in the interface class and clients cannot inline them, ever.
The argument for declaring the accessor inline is that this eliminates the call over-head, and can enable some further optimisations.
My experienced of measured performance is that the gain from doing this is usually rather modest. I consequently no longer do it by default.
More than being kind of global programming standards, these vary from organizations to organizaions. Of course, getLimit() would still be better than mere limit().

Member function definition

What is the right approach to take:
Define the member (class) function inside the class?
Define the member (class) function outside the class?
Thanks.
Assuming you're talking about these three possibilities:
Method defined in class definition in header file.
Method define outside class definition in header file.
Method define outside class definition in implementation file.
Then project and company guidelines may force you to use (1) or (3) always.
When you have a choice, it's IMHO best to adapt to circumstances at hand, considering things such as
Do you want a header-only module? Then (1) as default, (2) possible.
Is the method a large beast? Then (2) or (3).
Template method specialization? Then (2) or (3).
There is a build-time problem (slow builds)? Indicates (3).
Template class? (1) or possibly (2)
But except where the choice is effectively forced on you, above all consider the clarity of your code.
Cheers & hth.,
A common advice is to keep headers as simple and clean as possible. Headers will be included by external code, and they will have to process everything that you have written there. If you write a method in the header, all translation units will compile that function, only so that the linker can discard all but one of them later on.
If your code has an internal dependency on a type or library that is not part of your interface, then by inlining the code of the member function in the class declaration the definition of that class or the headers of that library will have to be included in your header, and that means that you are leaking your implementation details to your users.
Unless the member function definition is trivial (in an informal sense) and doesn't introduce any additional dependencies I would normally define a member function outside of the class body in a separate source file.
It's often a matter of style but there are some cases in which it is necessary and many other cases in which it is desirable to define function outside of the class body.
For example, in the cases where you have interdependent classes and only a forward declaration of another class can be made available before the class definition, a member function which uses the definition of that other class can only be defined outside of the class body after a full definition of the other class has been provided.
Do you mean "in the class declaration / .h file" vs "in a .cpp file using ::" ?
If so I always go for the latter. When it comes to debugging, it's a lot easier to step through and see what's going on. It also helps declutter the class declaration, which doesn't need to know any implementation details"
If you want to define a function within a class the most basic syntax looks generally like:
class Object
{
int property;
void doSomething()
{
property=100;
}
};
If you want to define a function outside it is similar to declaring functions before main and in library files. In your class you have:
class Object
{
int property;
void doSomething();
};
Then somewhere after your class, after the main() function or in an included file you can have the definition:
void Object::doSomething()
{
property=100;
}
Some place classes in a header file and the definitions in a cpp file used by that header. Various techniques possible.
Both of these approaches are valid. Often I will include very small and/or core class functionality directly within the class and other functions which do heavier bulk work I tend to separate. Try to think the difference in coming upon your code and wanting to alter it.
if we see according to performance issue than it is more effective way to declare the function in the class . becouse at the compile time it conects all the funcation calls and other components so it will easy and must be faster to get all in one source...

Declaration and Implementation of Functions

According to my teacher, it's bad practice to write user-defined functions like this:
int DoubleNumber(int Number)
{
return Number * 2;
}
int main()
{
cout << DoubleNumber(8);
}
Instead, he says to always use forward declarations, even if the functions don't need any knowledge of each other:
int DoubleNumber(int Number); // Forward declaration.
int main()
{
cout << DoubleNumber(8);
}
int DoubleNumber(int Number) // Implementation.
{
return Number * 2;
}
I find this especially strange since he made a point of telling us how important it is that the forward declaration and implementation are exactly the same or you'll get errors. If it's such a big deal, why not just put it all above main()?
So, is it really bad practice to declare and implement at the same time? Does it even matter?
If you don't declare the forward declarations ("prototypes"), then you need to make sure that all your functions occur before any functions that depend on them, i.e. in the reverse order of the call graph. That's fine for a simple example as above, but is a complete pain for anything more realistic (and in some cases impossible, if there are any loops in the call graph).
I think your teacher is an old C programmer.
If you wrote a C program without forward declarations and one function called another function declared later in the file (or in a different compilation unit), the compiler would not complain but silently pretend to know what the prototype should be.
Debugging is horrible, if you don't know if your compiler is passing the arguments correctly. Therefore it was a good defensive policy to always declare all functions; at least the compiler could raise an error if the declaration did not match the implementation.
C compilers and tool have gotten better (I hope). It is still not an error to call an unknown function, but GCC for example is kind enough to warn by default.
But in C++ you can't call a function that hasn't been declared or defined. Consequently, C++ programmers don't worry much about forward declarations.
Your teacher's policy is horrible IMHO. Use forward declarations only when they're really needed. That way, their presence demonstrates their necessity, which gives the reader useful documentation (i.e., there may be mutual recursion between the functions). Of course you do need forward declarations in header files; that's what they're for.
In my first programming class, the teacher also emphasized this point. I'm not exactly sure there is a benefit to such a simple case in actual software.
However, it does prepare you for using header files if you haven't covered that yet. In a typical case, you will have a header file custom-math.h and source file custom-math.cpp where custom-math.h contains the forward declaration and custom-math.cpp the implementation. Doing so may increase compilation time significantly when doing modifications to function implementations only in large projects. It is also a convenient way to split your program into "logical" groups of functions and/or classes.
If you are going to put other functions in the same file as main(), then what you do probably depends on your personal preference. Some people prefer to have main() close to the top to get to the program logic right away. In this case, forward declare your functions.
Karl Knecthel writes "Use forward declarations only when they're really needed. That way, their presence demonstrates their necessity, which gives the reader useful documentation (i.e., there may be mutual recursion between the functions)." and IMHO that's sound advice.
Oli Charlesworth talks about "complete pain" for ordering functions so that they can be called without forward declarations. That's not my experience, and I cannot imagine how that pain/problem is accomplished. I suspect a PEBCAK problem there.
A practice of using forward declarations for all functions will not save you from PEBCAK problems, but they do introduce needless maintainance work and needless more code to relate to, and they do make it more unclear which functions really need forward declarations.
If you get to the point where forward declarations could help to see function signatures at a glance, when forced to some very simple editor, then there are two actions that should be taken: (1) refactoring of the code, and (2) switching to a better editor.
Cheers & hth.,
Ask your teacher about why he recommends this ;) Anyway, it's not bad practice in my opinion, and in most cases it doesn't even matter. The biggest advantage of declaring all functions upfront is that you have a high-level overview of what the code does.
Traditionally you'll be sticking all your prototypes in a header file, so they can be used by other source files - or at least, you'll put the ones you want to expose in the .h file.
As far as code where it's not necessary, there's something to be said for putting all your file-level declarations at the top (variables and functions) because it means you can move functions around at-will and not have to worry about it. Not to mention, I can see every function in a file right away. But something like:
void Func1() { ... }
...
void Func2() { ... }
...
void Func3() { ... }
...
int main() { Func1(); Func2(); Func3(); return 0; }
That - that is to say, a number of disjointed functions all called by main() - is a very common file, and it's perfectly reasonable to forgo the declaration.
Blanket rules are rarely correct. The public api you would normally expose through the prototypes in the header file. The rest of the functions will likely to be in an anonymous namespace in the cpp file. If those are called multiple times in the implementation it make sense to provide prototypes at the top, otherwise every function using them would have to provide prototypes before calling functions. At the same time if some function is used multiple times in the cpp file it might be an indication that it's universal enough to be moved to a common api. If the functions are not used all over the place, it's better to provide as limited exposure to them as possible, i.e. declaring and defining them close to the place they are called from.
Personally, I like to only forward declare anything that client code needs to know about (i.e. in a class header). Anything that's local to a class implementation (such as helper functions), should be defined prior to usage.
Of course at the end of the day, for the most part, it boils down to either personal preference or coding standard that your project is following.