This question already has answers here:
Function with same name but different signature in derived class not found
(2 answers)
Closed 2 years ago.
I am passing different types of argument to the fun(), the code gets compiled, but still, the same function that prints "Class B" is getting executed. Shouldn't there happen overloading of functions?
Why does this happen?
#include <iostream>
using namespace std;
class A
{
public:
void fun(int x)
{
cout<<"class A"<<endl;
}
};
class B: public A
{
public:
void fun (char c)
{
cout<<"Class B"<<endl;
}
};
int main()
{
B obj;
obj.fun('c');
obj.fun(3);
}
B::fun() shadows A::fun() and an int literal is easily converted to char so your compiler had no difficulty with resolving that call. You can add using A::fun; to B's definition to make it visible.
When writing obj.fun(<argument>), first what fun to be called will be looked up. Since the compiler only looks at B first, it finds B::fun(char) both times, which is what is selected.
It would only look at A if there was no one parameter member function, so fun in B effectively hides fun in A. To overcome that, you can directly call A's fun like:
obj.A::fun('c'); // A
static_cast<A&>(obj).fun('c'); // A
Or you can bring A::fun(int) into B by using it:
class B: public A
{
public:
using A::fun;
void fun(char c)
{
std::cout << "Class B\n";
}
};
obj.fun('c'); // B
obj.fun(3); // A
You cannot overload like this across a heirarchy.
Name lookup happens before overload resolution and access control.
Once a function name is found in B, other classes up the heirarchy will not be checked. So all the candidate functions for a particular function call would be the functions present in B.
You will have to make the function name in A visible in B by saying:
using A::foo;
inside class B.
Now the overload will work as you expect.
Related
This question already has answers here:
What are the rules for calling the base class constructor?
(10 answers)
Closed 1 year ago.
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "Hello World";
}
};
class B:public A{
public:
B(){
cout << "World";
}
};
int main(){
B obj1;
return 0;
}
Why does this program print Hello WorldWorld, shouldn't it print World because I have created object of class B, so why is the constructor of A being called?
Conceptually, a base class becomes an unnamed sub object in the derived class, whose members are available in the same scope without extra qualification, and must be initialized.
You cannot avoid that initialization - which means a relevant constructor will be called or if it cannot be constructed then compiler will not allow you to inherit.
What you probably mean is whether the constructor should have overridden the base version, the simple answer is it cannot. If you want that effect - which will not work in constructors in a common sense way - you need to use virtual functions and overriding.
This question already has answers here:
Function pointer to member function
(8 answers)
Closed 4 years ago.
class Person;
class Command {
private:
Person * object;
//what is this? - a functor?...
void (Person::*method)();
public:
Command(Person *a, void(Person::*m() = 0): object(a),method(m) {}
void execute() { (object->*method(); }
};
// defining class Person here
class Person {
private:
string name;
Command cmd;
public:
Person(string a, Command c): name(a),cmd(c) {}
void talk();
void listen();
};
I was wondering what line 6 here means? Is that a way of defining a function or a functor? Also where does this type of function def appear and tends to be used? I found this example Under "Design Patterns" within Object Oriented Programming - this approach type is called Behavioural Command Pattern.
This is a pointer to Person class member taking no parameters and returning void.
Such initialization allows class Command referring to custom methods of class Person. Imagine class Person to be defined like this:
class Person
{
public:
void f1() { std::cout << "Call f1\n"; }
void f2() { std::cout << "Call f2\n"; }
};
Then we can create Command objects in this way:
Person p;
Command c1(&p, &Person::f1);
Command c2(&p, &Person::f2);
Executing these commands calls corresponding methods of given person:
c1.execute(); // prints "Call f1"
c2.execute(); // prints "Call f2"
This code line void (Person::*method)(); is a function pointer. void means that the function that is pointed won't return any data. (Person::*method)() is the definition of the pointer, the pointer will point to a void function.
In this page you can see how the syntax is:
Function Pointer Syntax
The syntax for declaring a function pointer
might seem messy at first, but in most cases it's really quite
straight-forward once you understand what's going on. Let's look at a
simple example:
void (*foo)(int);
In this example, foo is a pointer to a function taking one argument,
an integer, and that returns void. It's as if you're declaring a
function called "*foo", which takes an int and returns void; now, if
*foo is a function, then foo must be a pointer to a function. (Similarly, a declaration like int *x can be read as *x is an int, so
x must be a pointer to an int.)
The key to writing the declaration for a function pointer is that
you're just writing out the declaration of a function but with
(*func_name) where you'd normally just put func_name.
This question already has answers here:
virtual function default arguments behaviour
(7 answers)
Closed 9 years ago.
the below is my test code, i think it will output "Der:12", but the result is "Der:11", any one can tell me why output this, and where is the default argument store?
#include <stdio.h>
class Base{
public:
virtual void show(int i = 11)
{
printf("Base:%d\n", i);
}
};
class Der : public Base{
public:
virtual void show(int i = 12)
{
printf("Der:%d\n", i);
}
};
int main()
{
Base *p = new Der();
p->show();
return 0;
}
Hmmm, I'm not sure it's actually valid to override a virtual function with a different default parameter, and it's certainly not sensible. But on the other hand, the compiler is doing the right thing, even if it's contrary to your expectations.
Base *p;
p->show();
What happens here is that the compiler looks into Base for a function taking no arguments. There isn't one, but it finds the one-argument function and calls show(int) with the default parameter of 11.
But the function is virtual, and so because p's dynamic type is Der, it's Der::show(int) that actually gets called -- but crucially, still with Base's default argument of 11, but the default argument is looked up statically, not using run-time dispatch.
I haven't tried it, but I'd imagine if you said
Der *p = new Der();
p->show();
you'd get 12 output instead.
This question already has answers here:
Default constructor with empty brackets
(9 answers)
Closed 10 years ago.
I cannot do this:
class A
{
public:
A()
{
}
};
A a1();
Because A a1(); looks like a function prototype.
But I can do this:
class B
{
public:
B(std::string argument)
{
std::cout << argument;
}
};
B b1("Text");
These two things are essentially the same except the compiler is able to distinguish B b1("Text"); as NOT being a function prototype, because some data is passed in the parenthesis.
Is there any reason why the brackets must be omitted for A, or is the reason because the compiler thinks it is a function definition?
That's exactly it, and it's known as most vexing parse. The reason is that if A a1(); was treated as an object declaration, you wouldn't be able to declare a function with that prototype. And you want to be able to declare a function, right?
B b1("Text"); works because it can't be treated as a function prototype, but, for example, B b(A()); can and will.
This question already has answers here:
Default constructor with empty brackets
(9 answers)
Closed 7 years ago.
Consider the following code.
Here, A a(B()) compiles even though the constructor is A(B& b);
But print(B()) does not work. But print is also declared as print(B& b);
Why this inconsistency?
#include <iostream>
using namespace std;
class B{
public:
char b;
};
class A {
public:
B b;
A(B& b);
A() { }
};
A::A(B& b) {
this->b = b;
}
void print(B& b) { }
int main(){
print(B());
A a(B());
}
It compiles because it's not creating an instance of A. It's declaring a function named a that returns an A and receives one unnamed parameter of type pointer-to-function-returning-B. Since it's just a declaration, it compiles. If you're referred to a elsewhere in the code, you'd have seen additional problems. For why that's a function declaration instead of an object definition, the term to look up is most vexing parse.
This:
A a(B());
isn't doing what you think. It is actually parsed as a function declaration. This is commonly referred to as the "most vexing parse" in C++ (there are many posts here about it, if you search for that phrase).
You should not be passing a non-constant reference to a temporary, so the print statement should not compile. If you modify that reference in print to const, it will work.
Where you are trying to call the constructor you are actually declaring a function:
A a(B());
This declares a as a function returning A and taking as parameter a function pointer returning B and taking no parameters.
Actually trying to call the constructor results in an error, as expected:
A a = A(B());
tst.cpp:32: error: no matching function for call to ‘A::A(B)’