Is it true that for C++ to work similarly to OOP in Java, Ruby, Python, the function (or methods) must be declared virtual and what if not? - oop

Is it true that for C++ to work similarly in terms of modern OOP as in Java, Ruby, Python, the function (or methods) must be declared virtual and if not, what "strange" behaviors may occur?
I think it is true that for Java, Ruby, Python, and possibly other OOP languages that are late comers such as PHP and Lua, and even Smalltalk and Objective-C, all methods are just what is known as "virtual functions"?

"Method" is an unfortunately overloaded term that can mean many things. There's a reason C++ prefers different terminology, and that's because not only does it do something different from other languages, but it intends to do something different from what other languages do.
In C++ you call a member function. i.e. you externally make a call to a function associated with an object. Whether that function is virtual or not is secondary; what matters is the intended ordering of your actions - you're reaching into the object's scope, and commanding it to take a specific action. It might be that the object can specialize the action, but if so, it warned you in advance that it would do this.
In Smalltalk and the languages that imitate it (Objective-C most closely), you send a message to an object. A message is constructed on your side of the call consisting of a task name (i.e. method selector), arguments, etc., and the packed up and sent to the object, for the object to deal with as it sees fit. Semantically, it's entirely the object's decision what to do upon receipt of the message - it can examine the task name and decide which implementation to apply dynamically, according to a user-implemented choice process, or even do nothing at all. The outside calling code doesn't get to say what the object will do, and certainly doesn't get any say in which procedure actually runs.
Some languages fall in the middle ground, e.g. Java is inspired by the latter, but doesn't give the user any way to specify unusual dynamic responses - for the sake of simplicity every message does result in a call, but which call is still hidden from the external code, because it's entirely the object's business. C++ was never built on this philosophy of messages in the first place, so it has a different default assumption about how its member functions should operate.

The thing is that C++ is like the great grand father. It has many features, which often requires huge code definition.
Consider an example:
class A
{
virtual void fn() = 0;
};
class B: A
{
void fn();
};
#include "a.hpp"
#include "b.hpp"
int main()
{
A *a = new B();
a->fn();
}
This would implement overriding in C++.
Note that virtual void fn()=0 makes the class A abstract, and a pointer to base class (A) is essential.
In Java, the process is even simpler
abstract class A
{
abstract void fn();
}
class B extends A
{
void fn() {
//Some insane function :)
}
}
public static void main(String[] args) {
B ob = new B();
ob.fn();
}
Well, the effect is same; but the process is largely different. In short, C++ does have many features implemented in languages like Java, Ruby etc. but it is simply implemented using some (often complicated) techniques.
Regarding Php, since it is directly based on C++, there exists some syntax similarities between C++ and Php.

It is true that (for example) in Java all methods are virtual by default. In C++ it is possible to overload a non-virtual function (as opposed to overriding a virtual function) in a subclass, leading to possible counter-intutive behaviour, when only the base function is actually executed via a pointer or reference to the base class (i.e. when polymorphic behavior would normally be expected).
Because C++ is a value-based (as opposed to reference-based) language, then even when a function has been declared as virtual, the well known
object slicing problem can still arise: the superclass method is invoked when the type of a value object of a subclass is `cut down' to that of the base class (e.g. when the subclass is passed to a function which takes a base class argument by value).
For this reason, it is recommended to make all non-leaf classes abstract, something which is often achieved by providing a virtual destructor, even if such would otherwise be gratuitous.

Related

How do compilers compile virtual/overridden methods

I am developing a compiler for an object oriented language targeted on a virtual machine I wrote that I am using as a cross platform abstraction layer. I am sort of confused about how inherited methods works. Lets say I had the following lines of C# code.
class myObject : Object {
public int aField;
public override string ToString() {
return "Dis be mah object";
}
public void regularMethod() { }
}
Object test = new myObject();
Console.WriteLine(test.ToString());
Now this would output 'Dis be mah object'. If I called regularMethod however the compiled code would in reality do something like this:
struct myObject {
public int aField;
}
public static void regularMethod(ref myObject thisObject)
{
}
How would the inherited method ToString be handled after compilation? The compiler could not do what I did above with regularMethod, because if it did then 'Dis be mah object' would only be returned when creating myObject types and not plain Object types. My guess is that the struct myObject would contain a function pointer/delegate that would get assigned when a new instance is created.
If you are dealing with static overloading, it is really simple: you bind to the correct implementation when processing the code.
But, if you are working with dynamic overloading, you must decide things at runtime. For this you need to use dynamic dispatch, using the real object type. This is the same thign that is done with method overriding.
Dynamic dispatching is not the same as late binding. Here, you are chosing an implementation and not a name for your operation (despite the fact that this binding will occur at compile time, the implementation will only occur at runtime).
Staticly, you would only bind to implementation of the declared type of the object. It is done at compile time.
The are some mechanisms you could use to achieve the dynamic dispathing, it will dictate your language paradigm.
Is your language typed? Weakly typed?
C++, for instance, offers the two types of dispatch I mentioned. For the dynamic one (which I believe is the one you are interested), it uses a virtual table to do the mapping for one class. Each instance of that class will point have a pointer to that vtable.
Implementing
The vtable (one for all objects of same class) will have the addresses of all dynamicly bound methods. One of those addresses will be fetched from this table when a call is made. Type-compatible objects have tables with addresses with the same offset for the methods of all compatible classes.
Hope I've helped.

Check if a class implements an interface at run-time

Say FrameworkA consumes a FrameworkA.StandardLogger class for logging. I want to replace the logging library by another one (the SuperLogger class).
To make that possible, there are interfaces: FrameworkA will provide a FrameworkA.Logger interface that other libraries have to implement.
But what if other libraries don't implement that interface? FrameworkA might be a not popular enough framework to make SuperLogger care about its interface.
Possible solutions are:
have a standardized interface (defined by standards like JSR, PSR, ...)
write adapters
What if there is no standardized interface, and you want to avoid the pain of writing useless adapters if classes are compatible?
Couldn't there be another solution to ensure a class meets a contract, but at runtime?
Imagine (very simple implementation in pseudo-code):
namespace FrameworkA;
interface Logger {
void log(message);
}
namespace SuperLoggingLibrary;
class SupperLogger {
void log(message) {
// ...
}
}
SupperLogger is compatible with Logger if only it implemented Logger interface. But instead of having a "hard-dependency" to FrameworkA.Logger, its public "interface" (or signature) could be verified at runtime:
// Something verify that SupperLogger implements Logger at run-time
Logger logger = new SupperLogger();
// setLogger() expect Logger, all works
myFrameworkAConfiguration.setLogger(logger);
In the fake scenario, I expect the Logger logger = new SupperLogger() to fail at run-time if the class is not compatible with the interface, but to succeed if it is.
Would that be a valid thing in OOP? If yes, does it exist in any language? If no, why is it not valid?
My question stands for statically-typed languages (Java, ...) or dynamically typed languages (PHP, ...).
For PHP & al: I know when there is no type-check you can use any object you want even if it doesn't implement the interface, but I'd be interested in something that actually checks that the object complies with the interface.
This is called duck typing, a concept that you will find in Ruby ("it walks like a duck, it quacks like a duck, it must be a duck")
In other dynamically typed languages you can simulate it, for example in PHP with method_exists. In statically typed languages there might be workarounds with reflection, a search for "duck typing +language" will help to find them.
This is more of a statically typed issue than a OOP one. Both Java and Ruby are OO languages, but Java woudlnt allow what you want (as its statically typed) but Ruby would (as its dynamically typed).
From a statically typed language point of view one of the major (if not the major) advantage is knowing at compile time if an assignment is safe and valid. What you're looking for is provided by dynamically typed languages (such as Ruby), but isnt possible in a statically typed language - and this is by design (compile time safety).
You can, but it is ugly, do something like (in Java):
Object objLogger = new SupperLogger();
Logger logger = (Logger)objLogger;
This would pass at compile time but would fail at runtime if the assignment was invalid.
That said, the above is pretty ugly and isnt something I would do - it doesnt give you much and risks an unpleasant (and possibly suprising) exception at runtime.
I guess the best you could hope for in a language like Java would be to abstract the creation away from where you want to use it:
Logger logger = getLogger();
With the internals of getLogger deciding what to return. This however just defers the actual creation to further down - you'll still have to do so in a statically typed safe way.

Use of Constructors - Odd Doubt

I'm reading about constructors,
When an object is instantiated for a class, c'tors (if explicitly written or a default one) are the starting points for execution. My doubts are
is a c'tor more like the main() in
C
Yes i understand the point that you
can set all the default values using
c'tor. I can also emulate the behavior
by writing a custom method. Then why a c'tor?
Example:
//The code below is written in C#.
public class Manipulate
{
public static int Main(string[] args) {
Provide provide = new Provide();
provide.Number(8);
provide.Square();
Console.ReadKey();
return 0;
}
}
public class Provide {
uint num;
public void Number(uint number)
{
num = number;
}
public void Square()
{
num *= num;
Console.WriteLine("{0}", num);
}
}
Am learning to program independently, so I'm depending on programming communities, can you also suggest me a good OOP's resource to get a better understanding. If am off topic please excuse me.
Head First OOA&D will be a good start.
Dont you feel calling a function for setting each and every member variable of your class is a bit overhead.
With a constructor you can initialize all your member variables at one go. Isnt this reason enough for you to have constructors.
Constructor and Destructor functionality may be emulated using regular methods. However, what makes those two type of methods unique is that the language treats them in a special way.
They are automatically called when an object is created or destroyed. This presents a uniform means to handle the most delicate operations that must take place during those two critical periods of an object's lifetime. It takes out the possibility of an end user of a class forgetting to call those at the appropriate times.
Furthermore, advanced OO features such as inheritance require that uniformity to even work.
First of all, most answers will depend at least a bit on the language you're using. Reasons that make great sense in one language don't necessarily have direct analogs in other languages. Just for example, in C++ there are quite a few situations where temporary objects are created automatically. The ctor is invoked as part of that process, but for most practical purposes it's impossible to explicitly invoke other member functions in the process. That doesn't necessarily apply to other OO languages though -- some won't create temporary objects implicitly at all.
Generally you should do all your initialization in the constructor. The constructor is the first thing called when an instance of your class is created, so you should setup any defaults here.
I think a good way to learn is comparing OOP between languages, it's like seeing the same picture from diferent angles.
Googling a while:
java (I prefer this, it's simple and full)- http://java.sun.com/docs/books/tutorial/java/concepts/
python - http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/
c# - http://cplus.about.com/od/learnc/ss/csharpclasses.htm
Why constructors?
The main diference between a simple function (that also could have functions inside) and an Object, is the way that an Object can be hosted inside a "variable", with all it functions inside, and that also can react completly diferent to an other "variable" with the same kind of "object" inside. The way to make them have the same structure with diferent behaviours depends on the arguments you gave to the class.
So here's a lazy example:
car() is now a class.
c1 = car()
c2 = car()
¿c1 is exactly c2? Yes.
c1 = car(volkswagen)
c2 = car(lamborghini)
C1 has the same functionalities than C2, but they are completly diferent kinds of car()
Variables volkswagen and lamborghini were passed directly to the constructor.
Why a -constructor-? why not any other function? The answer is: order.
That's my best shot, man, for this late hours. I hope i've helped somehow.
You can't emulate the constructor in a custom method as the custom method is not called when the object is created. Only the constructor is called. Well, of course you can then call your custom method after you create the object, but this is not convention and other people using your object will not know to do this.
A constructor is just a convention that is agreed upon as a way to setup your object once it is created.
One of the reasons we need constructor is 'encapsulation',the code do something initialization must invisible
You also can't force the passing of variables without using a constructor. If you only want to instantiate an object if you have say an int to pass to it, you can set the default constructor as private, and make your constructor take an int. This way, it's impossible to create an object of that class without having it take an int.
Sub-objects will be initialized in the constructor. In languages like C++, where sub-objects exist within the containing object (instead of as separate objects connected via pointers or handles), the constructor is your only chance to pass parameters to sub-object constructors. Even in Java and C#, any base class is directly contained, so parameters to its constructor must be provided by your constructor.
Lastly, any constant (or in C#, readonly) member variables can only be set from the constructor. Even helper functions called from the constructor are unable to change them.

Is it bad practice for a class to have only static fields and methods?

I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.
Is it bad practice for a class to contain only static member variables and static methods?
No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.
EDIT: As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.
As long as the class has no internal state and is essentially what is known as a leaf class (utility classes fall into this category), in other words it is independent of other classes. It is fine.
The Math class being a prime example.
Sounds reasonable.
Note: Classes that do this often have a private no-arg constructor just so that the compiler yields an error if a programmer tries to create an instance of the static class.
Static methods don't worry me much (except for testing).
In general, static members are a concern. For example, what if your app is clustered? What about start-up time -- what kind of initialization is taking place? For a consideration of these issues and more, check out this article by Gilad Bracha.
It's perfectly reasonable. In fact, in C# you can define a class with the static keyword specifically for this purpose.
Just don't get carried away with it. Notice that the java.lang.Math class is only about math functions. You might also have a StringUtilities class which contains common string-handling functions which aren't in the standard API, for example. But if your class is named Utilities, for example, that's a hint that you might want to split it up.
Note also that Java specifically introduced the static import: (http://en.wikipedia.org/wiki/Static_import)
Static import is a feature introduced
in the Java programming language that
members (fields and methods) defined
in a class as public static to be used
in Java code without specifying the
class in which the field is defined.
This feature was introduced into the
language in version 5.0.
The feature provides a typesafe
mechanism to include constants into
code without having to reference the
class that originally defined the
field. It also helps to deprecate the
practice of creating a constant
interface: an interface that only
defines constants then writing a class
implementing that interface, which is
considered an inappropriate use of
interfaces[1].
The mechanism can be used to reference
individual members of a class:
import static java.lang.Math.PI;
import static java.lang.Math.pow;
or all the static members of a class:
import static java.lang.Math.*;
While I agree with the sentiment that it sounds like a reasonable solution (as others have already stated), one thing you may want to consider is, from a design standpoint, why do you have a class just for "utility" purposes. Are those functionals truly general across the entire system, or are they really related to some specific class of objects within your architecture.
As long as you have thought about that, I see no problem with your solution.
The Collections class in Java SDK has static members only.
So, there you go, as long as you have proper justification -- its not a bad design
Utility methods are often placed in classes with only static methods (like StringUtils.) Global constants are also placed in their own class so that they can be imported by the rest of the code (public final static attributes.)
Both uses are quite common and have private default constructors to prevent them from being instantiated. Declaring the class final prevents the mistake of trying to override static methods.
If by static member variables you did not mean global constants, you might want to place the methods accessing those variables in a class of their own. In that case, could you eleborate on what those variables do in your code?
This is typically how utility classes are designed and there is nothing wrong about it. Famous examples include o.a.c.l.StringUtils, o.a.c.d.DbUtils, o.s.w.b.ServletRequestUtils, etc.
According to a rigid interpretation of Object Oriented Design, a utility class is something to be avoided.
The problem is that if you follow a rigid interpretation then you would need to force your class into some sort object in order to accomplish many things.
Even the Java designers make utility classes (java.lang.Math comes to mind)
Your options are:
double distance = Math.sqrt(x*x + y*y); //using static utility class
vs:
RootCalculator mySquareRooter = new SquareRootCalculator();
mySquareRooter.setValueToRoot(x*x + y*y);
double distance;
try{
distance = mySquareRooter.getRoot();
}
catch InvalidParameterException ......yadda yadda yadda.
Even if we were to avoid the verbose method, we could still end up with:
Mathemetician myMathD00d = new Mathemetician()
double distance = myMathD00d.sqrt(...);
in this instance, .sqrt() is still static, so what would the point be in creating the object in the first place?
The answer is, create utility classes when your other option would be to create some sort of artificial "Worker" class that has no or little use for instance variables.
This link http://java.dzone.com/articles/why-static-bad-and-how-avoid seems to go against most of the answers here. Even if it contains no member variables (i.e. no state), a static class can still be a bad idea because it cannot be mocked or extended (subclassed), so it is defeating some of the principles of OO
I wouldn't be concerned over a utility class containing static methods.
However, static members are essentially global data and should be avoided. They may be acceptable if they are used for caching results of the static methods and such, but if they are used as "real" data that may lead to all kinds of problems, such as hidden dependencies and difficulties to set up tests.
From TSLint’s docs:
Users who come from a Java-style OO language may wrap their utility functions in an extra class, instead of putting them at the top level.
The best way is to use a constant, like this:
export const Util = {
print (data: string): void {
console.log(data)
}
}
Examples of incorrect code for this rule:
class EmptyClass {}
class ConstructorOnly {
constructor() {
foo();
}
}
// Use an object instead:
class StaticOnly {
static version = 42;
static hello() {
console.log('Hello, world!');
}
}
Examples of correct code for this rule:
class EmptyClass extends SuperClass {}
class ParameterProperties {
constructor(public name: string) {}
}
const StaticOnly = {
version: 42,
hello() {
console.log('Hello, world!');
},
};

What's wrong with Copy Constructors? Why use Cloneable interface?

When programming C++ we used to create copy constructors when needed (or so we were taught). When switching to Java a few years ago, I noticed that the Cloneable interface is now being used instead. C# followed the same route defining the ICloneable interface. It seems to me that cloning is part of the definition of OOP. But I wonder, why were these interfaces created, and the copy constructor seems to have been dropped?
When I thought about it, I came to the thought that a copy constructor would not be useful if one needs to make a copy of an object whose type is not known (as in having a reference to a base type). This seems logical. But I wonder whether there are other reasons that I do not know of, for which the Cloneable interfaces have been favored over copy constructors?
I think it's because there is no such inherent need for a copy constructor in Java and in C# for reference types. In C++ objects are named. You can (and you will most often) copy (and in C++1x move) them around e.g when returning from functions, since returning pointers require you to allocate dynamic memory which would be slow and painful to manage. The syntax is T(x) so it makes sense to make a constructor taking a T reference. C++ couldn't make a clone function, since that would require returning an object by value again (and thus another copy).
But in Java, objects are unnamed. There are only references to them, which can be copied, but the object itself isn't copied. For the cases when you actually need to copy them, you can use the clone call (but i read in other anwers clone is flawed. i'm no java programmer so i cannot comment that). Since not the object itself is returned, but rather a reference to it, a clone function will suffice. Also a clone function can be overriden. That's not going to work with copy constructors. And incidentally, in C++ when you need to copy a polymorphic object, a clone function is required too. It's got a name, the so-called virtual copy constructor.
Because C++ and Java (and C#) aren't the same thing. C++ has no built-in interfaces because interfaces aren't part of the language. You can fake them with abstract classes but they aren't how you think about C++. Also, in C++ assignment is normally deep.
In Java and C# assignment just involves copying the handle to the internal object. Basically when you see:
SomeClass x = new SomeClass();
in Java or C#, there's a level of indirection builtin that doesn't exist in C++. In C++, you write:
SomeClass* x = new SomeClass();
Assignment in C++ involves the dereferenced value:
*x = *another_x;
In Java you can get access to the "real" object as there is no dereference operator like *x. So to do a deep copy, you need a function: clone(). And both Java and C# wrapped that function into an interface.
It's the issues of final type and of cascading the clone operation through the super classes which is not addressed by copy constructors - they are not extensible. But the Java clone mechanism is widely considered badly broken too; especially problems where a subclass does not implement clone(), but inherits from a superclass that implements cloneable.
I strongly recommend you research cloning carefully, whatever path you choose - you will likely choose the clone() option, but make sure you know exactly how to do it properly. It's rather like equals() and hashCode() - looks simple on the surface, but it has to be done exactly right.
I think you haven't get the right point. I give you my two cents.
Fundamentally there's a problem: creating a clone of a class without knowing the exact class type. If you use copy constructor, you cannot.
Here is an example:
class A {
public A(A c) { aMember = c.aMember }
int aMember;
}
class B : A {
public B(B c) : base(c) { bMember = c.bMember }
int bMember;
}
class GenericContainer {
public GenericContainer(GenericContainer c) {
// XXX Wrong code: if aBaseClass is an instance of B, the cloned member won't
// be a B instance!
aBaseClass = new A(c.aBaseClass);
}
A aBaseClass;
}
The Clone method, if declare virtual, could create the right class instance of the generic member.
An this problem is common to every language, C# C++ or Java...
Maybe this is what you was meaning, but I cannot understand this from any answer.
Just wanted to add that in Java the copy constructor is not completely useless.
There are cases where your class has a private instance variable of a mutable non-final type, e.g. Date, and has a setter and getter for the variable. In the setter, you should make a copy of the given date, because the caller could modify it later and thereby manipulate your object's internal state (usually by accident, but maybe intentional). In the getter, the same precaution is required.
The defensive copy could be implemented by calling clone() (the class Date is cloneable), but a malicious caller could call the setter with a subclass of Date which overrides the clone() method with {return this;}, and so the caller might still be able to manipulate your object. This is where the copy constructor comes into play: By calling new Date(theDate), you are sure to get a fresh Date instance with the same timestamp as the given date, without any connection between the two date instances. In the getter, you could use the clone method, because you know the private variable will be of class Date, but for consistency, usually the copy constructor is used there, too.
Also note that the copy constructor would note be required if the Date class was final (calling clone() were safe) or immutable (no copy required).
I think its only because once u have defined a copy constructor, you could never pass the reference itself again. (Unless it would have a function that does that...but thats not any easier than using the clone() method.)
In C++ its not a problem: you can pass the whole object or its reference.