How does class casting work? - casting

Consider c1 is the base class of c3. The below code works perfectly.
c1 obj1=new c3();
c3 obj2=(c3)obj1;
But, There is a ClassCastException in the below one
c1 obj1=new c1();
c3 obj3=(c3)obj1;
What have I missed?

I think what's happening is that you are creating obj1 as an instance of c1, and then trying to cast it to class further down the inheritance chain than c1.
In your first example, c1 is a base type of c3 and so you can create an instance of c3 where the type is c1..that's fine. c3 is a child of c1 and so inherits all its properties and methods.
In the 2nd example, however, you are creating an instance of c1 with a type of c1. You are then trying to cast it to its child. A child class may have additional properties and methods that the parent doesn't have.
To summarise, a child can be of its parent type and cast to it, however, a parent cannot be its child and cannot be cast as such.
If you need further clarification, let me know.

Related

Preventing descendants from overriding method

In C++ (11/14/17, I don't care), I have a base class B which exposes method x as protected.
In class D1, which derives from B, I want to prevent further descendants (of D1) from calling x(). Now, if I were overriding x in D1, I would simply mark it as final.
But, what if D1 does not override x(), yet D1 still wants to hide it from descendants? How can I do that?
How can I do that?
By changing the program and overriding x in D1. You can just delegate to the base class version by calling it.

How does C++ multiple inheritance virtual function access derived class field?

Referencing the multiple inheritance memory layout, suppose Derived class has a field called int derived_only. If I have a Base1 * b1 and Base2 * b2, both pointing to the same Derived class object, then according to wiki, b1 and b2 have slightly different values due to pointer fixup. My question is, if I call a virtual function, say the virtual clone(), by using either b1 or b2, how does clone() calculate derived_only's address, from either b1 or b2?
Basically, when calling b1->clone() vs b2->clone(), the this pointer passed in is different, then how does clone() know how much offset to add to this to get to derived_only?

Unit test on legacy code, object creation

I am adding unit tests to an existing application. The class relationship is like this:
class TopClass creates class A and B and common class AB;
class A creates class A1, A2, A3, A4 and AB;
class B creates class B1 and AB;
I am told to pass all depended objects (as interface) when creating the top level object in order to do dependency injection. So class Constructors need to be changed as this:
TopClass(A a, A1 a1, A2 a2, A3 a3, A4 a4, AB ab, B b, B1 b1)
A(A1 a1, A2 a2, A3 a3, A4 a4, AB ab)
B(B1 b1, AB ab)
Is it the right/good way? Is there a way that no need to create all objects at the beginning of the application?
No, that is not a good way.
If possible, you should only have to pass in interface A and interface B
TopClass(A a, B b)
This way unit tests for TopClass only worry about its direct dependencies and not dependencies of dependencies. This will also let you mock out implementations of A and B in your tests.
Then for tests of Ayou might have a constructor that passes in A1, A2 etc but TopClass shouldn't know about that.
Short answer: Yes, that's where you start, but it's not necessarily a good ending point. TopClass should care only about (interfaces of) A, B, and AB. The implementations and dependencies of those objects are not relevant to TopClass. This also means that mocking TopClass should be very simple: You need a mock A, a mock B, and a mock AB, and you can pass those in directly.
How do you create an A without caring about A's dependencies? Instead of an A instance, receive a Provider<A>, where Provider is Java's built-in no-argument factory interface.
At that point, your constructors look as follows:
TopClass(A a, B b, AB ab)
A(A1 a1, A2 a2, A3 a3, A4 a4, AB ab)
B(B1 b1, AB ab)
Where any of those types could be replaced with a Provider<Type> if you want to delay creation until you need it, or if you need more than one.
"But wait!" I hear you cry. "Doesn't that mean I have to make a complicated series of boilerplate Providers in order to hide the implementation/dependency details from TopClass?" Yes, it does, and you can do that manually--or you can use a dependency injection framework like Spring, Guice, or Dagger.
A manual one would look something like this:
public class EntryPoint() {
AB ab = new AB();
Provider<TopClass> provideTopClass() {
return new Provider<TopClass>() {
#Override public TopClass get() {
return new TopClass(provideA().get(), provideB().get(), provideAB().get());
}
};
}
Provider<A> provideA() {
return new Provider<AB>() {
#Override public AB get() {
return new A(provideA1().get(), provideA2.get(), ...);
}
};
}
Provider<AB> provideAB() {
return new Provider<AB>() {
#Override public AB get() {
return ab; // always reuse the same instance if you'd like
}
};
}
// and so forth
}
There, you've just extracted all of the creation and wiring into one class, which Guice can emulate at run-time and which Dagger can generate directly at compile-time. You'll need to work with your team to choose a framework you want, or start manually, but overall this should provide a lot of rewards in making an easy-to-assemble and easy-to-test application.
If you create the instances in this order:
AB ab = new AB();//and so on for all classes wihtout dependencies like a1, a2, ..., b1
A a = new A(a1, a2, a3, a4, ab)
B b = new B(b1, ab)
TopClass(a, b, ab)
But as you say, that TopClass creates instances of those classes, that is the actual problem. it should expect instances, not create them.
Maybe this way it doesn't even need the ab parameter if it only uses it for creating A and B.
Using some Dependency Injection Framework/Library can be one way of taking a lot of boilerplate away from the developer, but its costs like
efford for changing code to make it work in application and tests
runtime performance (depending on the framework)
should be considered.

How to emit signal through a few class objects in Qt?

I have a few classes: Class A - highest class, Class B and Class C which are initialized in Class A constructor. In Class B constructor is initialized Class B1 and in Class C constructor is initialized Class C1. C1 object and B1 object does not see each other.
Every time I need to send signal from C1 class to B1 class, I connecting C1 and C, C and B, finally, B and B1. So every time my programm emitting a signal in C1 class object, it is sending to C class object then to B and then to B1. (On image) Is it a right Qt Way? Or there is a better way to do that?
You could add to class C an interface which returns C1 and a similar interface to class B, too. Then after creating classes C and B, class A could ask C1 and B1 and connect C1's signal to B1's slot.
Or, if you have lots of these kind of cases and you definitely don't want to expose classes C1 and B1 to A, you could create your own signaling mechanism. Some kind of "post office" where classes could register as receivers and to where classes could send messages. In this case, class B1 would register as a receiver and class C1 would send messages. C1 and B1 would know nothing about each other. The post office class would send C1's message to B1. This kind of "post office" class could also be implemented using Qt's signals and slots.

Getting the pointer in C++ for a class that is part of another class with multiple inheritance

I have some classes that inherit from each other but they do so using templates. What I want is to effectively get a pointer and/or reference to one of the base classes as if it is one of the other possible derived classes dependant upon the templates
class a1
{
public:
int a;
virtual void func()
{
}
// other non virtual functions ...
};
class b1
{
public:
//no members or virtual functions
//other non virtual functions ...
};
class a2
{
public:
int a;
// ...
};
template < class T1 >
class derived : public T1,
public a2
{
int a;
// ...
};
Class derived can either inherit from class a1 or class b1, this is mostly to save space in derived as b1 is a blank class and so when derived is instanciated with template paramater b1 it is not carrying the extra load of the data members and virtual functions of a1.
However I now want to get a pointer or reference from derived(a1) that is really a pointer or reference for a type derived(b1).
What i'm really asking for is help on a "good" way of doing offsetof() but using inheritance where I can get the offsetof() a2, this I am assuming is a good pointer for derived(b1) because b1 is a blank class.
I have tried to get the pointer of derived(a1) object then add on the sizeof(a1) with the hopes that this will be the correct position but wanted to know if anyone else had suggestions of a better way.
As far as I understand you, you have e.g. a pointer to derived<a1>, and want a pointer to a1. Since a1 is a direct base class of derived<a1>, you can obtain this pointer by direct implicit casting:
derived<a1>* instance = whatever();
a1* pointer = instance;
It is however recommended that you make the cast explicit. Since this class is always safe and can be resolved at compile-time, use static_cast.
a1* pointer = static_cast<a1*>(instance);
Executive summary: Pointer arithmetics is something you should not do for traversing class hierarchies. There are static_cast and dynamic_cast available for exactly this purpose: They will warn you or error out when you try to do something dangerous, and generally have much more knowledge about the exact memory layout than you can ever have.
EDIT: You edited the question to say that you want to cast from derived<a1> to derived<b11>. This is not possible. static_cast and dynamic_cast do not support operations that change the memory layout of instances. Any pointer arithmetic is strongly advised against because you cannot know how the compiler arranges the data fields of instances in memory.
Have class b1 as the base class of class a1
If all you want to do is to save memory space for some of your objects then templates are probably not the best tool for that.
As b1 is empty derived<b1> adds nothing useful to a2, so why not using a simple inheritance class a1 : public a2 ? You can instantiate objects from either a1 or a2 depending if you need the additional data and they can all be casted to a2 (for example, if you want to store them in a list).
If you weren't using templates and just Multiple Inheritance, assuming that d is an instance of type Derived but is referenced as A1 you could have.
A1* a = new Derived();
Derived* d = (Derived*)a;
B2* b = d;
The template complicates things though.