Reputation: 47
Coming from a good foundation in java to c++, I'm really confused on why when we use the cmath library we don't have to call it like: classname.function like we do in java (ex: Math.sqrt()). I saw that we can just call sqrt(). How does it know which class this method is coming from. I also wasn't able to see wether this function is static or not or any visibility type on cppreference.com so it did not help to give me a clue either.
Upvotes: 1
Views: 137
Reputation: 70367
It doesn't come from a class. Not every function in C++ is a class method. In fact, most of them aren't. Functions in C++ (and in many languages; Java is really the oddball here) can be standalone and can simply be called as-is.
Likewise, top-level functions can't be "static" in the Java sense, since they don't belong to a class. static
is a keyword in C++, and inside a class it's similar to Java's definition, but you won't find yourself using it very often in C++. Outside a class, "static" means something totally unrelated.
The headline here is: Forget most of what you know about Java. Low-level control flow, like loops and conditionals, will mostly carry over. But C++ classes are a different beast, memory management in C++ is entirely different, and the way you structure your program is different.
Java paradigms work in Java, but if you follow those paradigms in C++, you'll make everything a (raw) pointer, stick everything inside of a class, and litter new
calls throughout your program. I've seen code that's written like this. I've had professors who were obviously Java coders forced to teach C++, and it shows. Learn C++ as its own language, not as "diet Java". I cannot stress that point enough.
Upvotes: 6
Reputation: 3319
In C++ you may opt to use namespace
to achieve exactly that. For example you may declare function doSomething
within namespace Math
and then you refer to that function as Math::doSomething
.
Upvotes: 0