Hi, recently I was wondering what happens underneath during compile time
when running the code below.
why is the function of class B not called?
Is it because you have two clashing definitions and one overrides the other?
I thought "A * ptr" was just a declaration
why is it when I allocate a B object and call it`s function
it even knows about the function of A. What do I read to
understand more?
#include <iostream>
class A {
public:
void foo()
{
std::cout << "This is A \n";
}
};
class B : public A{
public:
void foo()
{
std::cout << "This is B \n";
}
};
int main()
{
A * ptr = new B();
ptr->foo();
system("pause");
}
#include <iostream>
class A {
public:
A()
{
std::cout << "This is A CTR \n";
}
void foo()
{
std::cout << "This is A \n";
}
};
class B : public A{
public:
B()
{
std::cout << "This is B CTR \n";
}
void foo()
{
std::cout << "This is B \n";
}
};
int main()
{
A * ptr = new B();
ptr->foo();
system("pause");
}
#include <iostream>
class A {
public:
A()
{
std::cout << "This is A CTR \n";
}
void foo()
{
std::cout << "This is A \n";
}
};
class B : public A{
public:
explicit B(int a)
{
std::cout << "This is value A = " << a << std::endl;
}
explicit B()
{
std::cout << "This is B CTR \n";
}
void foo()
{
std::cout << "This is B \n";
}
};
int main()
{
A * ptr = new B(1.5f);
ptr->foo();
system("pause");
}