Question

ClassA.h

@interface classA

-(void)print1;
-(void)print2;

@end

ClassA.m

-(void)print1 {
    NSLog(@"I am class A 1");
}

-(void)print2 {
    NSLog(@"I am class A 2");
}

ClassB.h

@interface classB : classA

-(void)print1;

@end

ClassB.m

-(void)print1 {
    NSLog(@"I am class B");
}

AppDelegate.m

ClassA *a1 = [[ClassB alloc]init];
    [a1 print1];
    [a1 print2];

Output

I am class B
I am class A 2

Error

ClassB *a1 = [[ClassA alloc]init];

Question

ClassB is child of ClassA means ClassB has ClassA functionalities and its own also. But ClassA don't know that ClassB is its child.

So how classA *a1 = [[classB alloc]init]; is working and giving the above output and classB *a1 = [[classA alloc]init]; is giving error

Was it helpful?

Solution

[[classB alloc]init]
- this is the part where you actually create the object, whereas
classA *a1
is only a declaration of, to put it simply, what will be "expected" from this object to be. Your classB is a subclass of classA, so it has everything classA has, and therefore won't cause errors when accessing properties or using methods.
On the other hand, when you create a classA instance and cast it to classB:
classB *a1 = [[classA alloc]init]
the compiler will expect this object to do what classB is able to do, and since classB is a classA extension, it might cause errors.

OTHER TIPS

For the case of classA *a1 = [[classB alloc]init]; is working because in objective-C, methods are resolved at run time. [a1 print1] sends a message to a1 object which could be anything at the run time to invoke method print1. Even you can call [a1 some_random_method] where compiler will give warning but not error. Since, it is possible that in runtime, some_random_method can be added.

For the second case classB *a1 = [[classA alloc]init];, I think you get the error because of the concept that not all classA is classB.

It is possible that classB has extra members and methods. By typecasting classA object to classB, you will try to access those extra members and methods which has undefined behaviour. So, compiler does not support implicit typecast from classA to classB and gives error.

However, you can explicitly typecast classA object to classB. In runtime, you can add methods which are special to classB to this object (objective-C supports adding methods in runtime) and call them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top