You may use static_cast
A *b = new B;
B *bb = static_cast<B*> (b);
through bb you can access Func2()
.
문제
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
해결책 2
You may use static_cast
A *b = new B;
B *bb = static_cast<B*> (b);
through bb you can access Func2()
.
다른 팁
There are a few problems in your code.
Void
instead of void
. Notice the uppercase vs lowercase difference.Funct1
in A
but Func1
in B
. You can change Funct1
to Func1
;
at the end of B
.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:
Use B b
instead A b
.
B b;
b.Func1();
b.Func2();
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.