Question

Suppose I have the following code:

class A 
{
     public:
         void Funct1();
};

class B : public A
{
      public:
          void Func1();
          void Func2();
}

In main()

Declaring Object of type A

  A b = new B;
  b.Func1() // can access it;
  b.Func2() // cannot access

How can I make or access Func2 using object b especially in main

Was it helpful?

Solution 2

You may use static_cast

A *b = new B;
B *bb = static_cast<B*> (b);

through bb you can access Func2().

OTHER TIPS

There are a few problems in your code.

  1. You are using Void instead of void. Notice the uppercase vs lowercase difference.
  2. You are using Funct1 in A but Func1 in B. You can change Funct1 to Func1
  3. There is a missing ; at the end of B.
  4. Using B instead of new B. You have:

    A b = new B;
    

    That is a syntactically incorrect line. You can make it either

    A b = B();
    

    or

    A* b = new B();
    

Even after that change, you still have the problems you described.

There are two ways you can solve this:

  1. Use B b instead A b.

    B b;
    b.Func1();
    b.Func2();
    
  2. Use a virtual member function.

     class A 
     {
          Public:
              void Func1();
              virtual void Func2();
     };
    
     class B : public A
     {
           Public:
               void Func1();
               virtual void Func2();
     };
    

    Then, you can use:

    B b;
    A* aPtr = &b;
    aPtr->Func1();
    aPtr->Func2();
    

Write a function which gets argument of Type A. Then you can send an argument of type A or B to this function,polymorphism works and the function inside class A or B works wrt what you want.

In a statically typed language like C++, you can only call methods corresponding to the static type of an object in the current scope. In main, you declared b with static type A, restricting it to the interface defined in class A. If you want polymorphism, you need to declare the polymorphic functions in A and also add the virtual keyword.

If object-oriented programming doesn't make sense for the problem you are trying to solve, don't use it. In C++, you don't need to put everything in classes, let alone in class hierarchies. Start with simple free-standing functions and use classes if you need them.

That being said, if you really insist, use dynamic_cast. In some situations, this may even be a legitimate choice. But if you feel that you need it all the time, then you must review your understanding of object-oriented programming.

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