Why do we have a virtual destructor and not a virtual constructor in c++? - virtual-destructor

Why can we have a virtual destructor but not virtual constructor?

The constructor chain can be determined at compile time, because you use new ClassName() always from the most specific class possible.
However you call destructors on possibly parent classes if you use polymorphism, so you can't know at compile time where to start the chain from. You need a virtual function to always call the right one (or you'd end up with potentially uncleaned resources in the most specific classes).

Related

What's the correct way of thinking C# protected accessor in swift?

In c# we have the protected accessor which allows class members to be visible on inherited clases but not for the rest.
In Swift this doesn't exist so I wonder what's a correct approach for something like this:
I want to have a variable (internal behavior) and and a public method using this variable on a base class. This variable will be used also on inherited clases.
Options I see
Forget about base class and implement variable and methods everywhere I need it. WRONG, duplicated code
Implement inheritance by composition. I'd create a class containing common methods and this will be used by composition instead of inheritance. LESS WRONG but still repeating code that could be avoided with inheritance
Implement inheritance and make variable internal on base class. WRONG since exposes things without any justification except allowing visibility on inherited clases.
Implementation Details for Base Class
I want to have a NSOperationQueue instance and and a public method to cancel queued operations. I add new operations to this queue from inherited classes.
In Swift the correct answer is almost always protocols and extensions. It is almost never inheritance. Sometimes Cocoa stands in our way, because there are classes in Cocoa more often than protocols, but the goal is almost always protocols and extensions. Subclassing is our last choice.
Your particular case is confusing because NSOperationQueue already has a public method to cancel queued operations (cancelAllOperations). If you want to protect the queue from outside access (prevent callers from using addOperation directly for instance), then you should put the queue inside another type (i.e. composition), and forward what you want to the queue. More details on the specific problem you're solving would allow us to help suggest other Swift-like solutions.
If in the end you need something that looks like protected or friend, the correct solution is private. Put your subclass or your friend in the same file with the target, and mark the private thing private. Alternately, put the things that need to work together in a framework, and mark the attribute internal. The Swift Blog provides a good explanation of why this is an intentional choice.

Calling methods on objects from 'opposite ends' of a program

I have been developing my skills at creating large object orientated programs (30+ classes).
I am trying to make my code as clean as possible after reading a fantastic book called clean code.
One problem I am having is to do with calling a method on an object from "across the program"
Say I have 5 classes.
`ClassA
ClassB
ClassC
ClassD
ClassE`
an instance of ClassA contains an instance of ClassB, which in turn contains an instance of classC, so
`ClassA > ClassB > ClassC`
I'm not saying that this is the inheritance chain, rather that in the constructor of classA an instance of ClassB is created and so on.
Now, say that ClassD > ClassE in a similar way. ClassD is instansiated with an instance variable containing an instance of ClassE.
This is all well and good, and the classes are small and only handle one job, and it all seems nice and clean.
However, say that at some point in the program I need the instance of classC to call a method on the instance of ClassE.
The two objects are on 'opposite sides of the program' so to speak. Yet the method call is necessary.
I am left with three options as I see it
make the instance of classE a global variable, so that classD AND classC can access it (as well as anything else in the program). I feel like this is bad form as global variables are generally considered bad news
Create the instance of ClassE at the top level, then pass it in as an argument to the constructors of ClassA, ClassB, and ClassC. The trouble with this is that I would end up with really long constructor argument lists if this is happening more than once, and it seems like lots of work to pass ojects down chains of constructors like this
Move the object of ClassE to be instantiated by ClassC. The trouble with that is that its more strongly coupled with ClassD and only needs to be called once in the entire running of the program by ClassC.
So what do I do in situations such as these? And are there any resources I can read about this. I know that I could use the observer pattern for situations similar to this, but when its just for one method call it seems excessive, as I would be making things observable all over the program. I want my code as clean as possible!
Thanks in advance :)
Three words: Single Responsibility Principle. If you worry that your class has too many constructor arguments it's probably because this class needs to deal with too many different things. If you keep classes focused, they will be small.
You correctly indicate the coupling problem in the third solution you've described. The coupling problem is also present in the first solution (depending on a global variable is even harder to find/diagnose later). So the second option seems to be the best - as long as you refactor the code to keep your classes simple.
You could read up on Law of Demeter (Short explanation on wikipedia: http://en.wikipedia.org/wiki/Law_of_Demeter or a longer but very well written example http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf)
Depending on the context / content of your example you could for instance: Build your Class D as a wrapper to your class E (or similar facade / adapter). Meaning if your class c sometimes needs to talk to an E instance it does so via it's class D instance.
Another way to go would be to provide a reference to a class E instance to those objects that need one.
If all your objects are talking to the same instance of E you could also think about the singleton pattern where there is only one instance of a class. But this instance is more or less globally available.
Give a bit more context info and we can develop this further.
EDIT: btw. a funny explanation of lad of demeter can be found here:
http://www.daedtech.com/visualization-mnemonics-for-software-principles
EDIT Nr.2 (your comment): ad. 1.) Maybe you can implement your class D in a way that reliefs your other classes of ever talking directly to an E object. Instead they ask their D instance to do something (not knowing that D delegates the call to E). Depending on what you are trying to do this might be an option for you.
ad. Singleton.) Yes and No. The Singleton main use is that it guarantees (if implemented correctly) that only one instance of the singleton object exists. If you are talking about config settings this might not be a requirement. You are right however that basically the thing is kind of a global variable with all it's downsides. Your object D sounds as if it's immutable in a sense that it does not change it's state while your program is running so maybe the problem is not that you create a complex dynamic behaviour but that you create too many dependencies.
Just another link/principle to get you thinking:
What is Inversion of Control?

PostSharp intercept class constructor and destructor calls

Is it possible to intercept class constructor and destructor calls using PostSharp? I would like to create active instances counter for classes.
You can use OnMethodBoundaryAspect on constructor and destructors. Note that classes don't have destructors by default in C# and VB, and destructors are called at a non-deterministic moment.
Remember that constructors can be called in chain, and the aspect is going to be applied on every constructor in the chain.

FXCop rule Interface methods should be callable by child types

When running FxCop I get the error that interface methods should be callable by child types.
The resolution states the following:
"Make 'MenuPreview' sealed (a breaking change if this class has previously shipped),
implement the method non-explicitly, or implement a new method that exposes
the functionality of 'IComponentConnector.Connect(int, object)'
and is visible to derived classes."
I get this for all classes the derive from Window or some other UI class. Is this a red herring that I can ignore, or is there something I should be doing?
I think the issue is that if an interface is implemented explicitly, it will be impossible for a derived class to both change the interface behavior and make use of the base-class behavior. A common pattern to get around this difficulty in cases where explicit interface implementation would be required is to have the interface do nothing but call a protected virtual method, and have any derived classes that wish to override the behavior of the interface do so by means of the protected virtual method.
Consider IDisposable.Dispose(). If the code in an explicit implementation were actually responsible for performing the disposal, there would be no way for a derived class to add its own dispose logic except by reimplementing IDisposable, and there would be no way for a class which reimplemented IDisposable to access its parent's Dispose method. Although Microsoft could have had IDisposable.Dispose call a protected function with a different name, it opted to use the same name but add a dummy parameter of type Boolean.

Adding methods to an Objective C class interface is optional?

Coming from a C++ background, one thing that confuses me about Objective C is the fact that you can add a method to a class without actually specifying it in the class interface. So I had a barrage of questions:
Why would someone choose to not add the method in the class interface?
Is it simply because of visibility?
Methods without a declaration in the interface are private?
Is declaring methods in a class interface just optional?
Is it different for overriding a base class' method?
The main difference is that C++ sets up much of its inheritance and types at compile time and Objective C does it mostly at runtime.
The only differences in putting a method in the interface (if all parameters are objects) in objective-C are that the compiler can see it at compile time and check that an object could respond to the method - if it does not then you get a warning but the compilation does succeed and the program will run and loo for the method at runtime. If the method is in the implementation of the class or a category (or some other way) then the run time will find it and call it successfully.
There are NO private methods you can call any method.
I believe that this is the only way to create private methods in Objective-C. The language does not support the ability to declare a private method so by not declaring a method in the header file you are making private from all callers.
Proper data encapsulation requires that you lock down access to members that either expose data or manipulates it. Not all members ought to be exposed.
Yes it is.
Yes, this is true.
Yes, this is true as well.
This I am not sure about - perhaps someone with more Objective-C knowledge could answer this one.
Extending Andrew Hare's answer to answer 5, no, it doesn't: whether declared in an #interface or otherwise, method replacement/refinement works the same.