Why can I use the constructor without an object declaration? - c++

Why can I use the constructor without a previous object declaration? And, if the previous works, why do I get an error when using k()?
Here is my code:
#include <iostream>
using namespace std;
class Test
{
int i, x;
public:
Test(int ii = 0)
{
cout<<"WOW!";
cout<<i<<" ";
i=ii;
}
void k()
{
cout<<i<<" ";
}
};
int main()
{
Test();
k(); ///k was not declared in this scope
return 0;
}

Why can I use the constructor without a previous object declaration?
A constructor is used to create a new object. So it can't be called on a previous object.
And, if the previous works, why do I get an error when using k()?
Because k() is a non-static method of Test, so it needs a Test object to call it on. You can't call it as a standalone function.
int main()
{
Test t;
t.k();
return 0;
}

You can create instance of the class because the name of the class can be found with name lookup from the current (the global in this case) namespace, and the class has been defined.
You haven't declared a free function by the name k, so you cannot call such function.

Related

Use of parametrised constructor is giving error

I've been trying to learn about parametrised constructors:
Here is the program I wrote:
#include <iostream> //Using a parametrised constructor i.e. we give an integer value as a parameter
using namespace std;
class item{
int cost;
int price;
public:
item (int a){
cost=a;
}
void display(){ //Display is not a constructor, hence we need to specify its return type and parameters
cout << cost;
}
} item1;
int main(){
item1(5);
item1.display();
return 0;
}
However, I get an error on Visual Studio Code:
call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
Can anyone tell me what's wrong with the code?
At the end of class creation you are asking to create an object named item1 but you are not providing any value, that's why it is throwing error you cannot create an object without '('.
After object creation you can't call the constructor. you can access all the methods and fields.
#include <iostream> //Using a parametrised constructor i.e. we give an integer value as a parameter
using namespace std;
class item{
int cost;
int price;
public:
item (int a){
cost=a;
}
void display(){ //Display is not a constructor, hence we need to specify its return type and parameters
cout << cost;
}
} item1(5);
int main(){
item1.display();
return 0;
}

why can we access a non_member function from member function in c++

The following code compiles without any warning or error:
#include <iostream>
using namespace std;
class demo_class
{
int x;
float y;
public:
void fun(void);
};
void fun2(void)
{
cout<<"i am fun2\n";
}
void demo_class::fun(void)
{
cout<<"i am fun\n";
cout<<"i can call fun2\n";
fun2();
}
int main()
{
demo_class ob1;
ob1.fun();
return 0;
}
I am not understanding that as the scope of fun function is only in demo_class
then how can it call fun2 function, should not it show error as the access of fun function only within the demo_class?
Name lookup would try to examine all the possible scopes, until it finds at least one at any scope, then the name lookup stops.
In this case, the name fun2 can't be found at class scope, then the further scope, i.e. globle scope is examined and ::fun2 is found.
There is no reason to disallow calling a free function from within a member function. If this was the case classes would be rather useless (they would be a way to prevent code reuse instead of supporting it).
As mentioned in a comment, in cout<<"i am fun2\n"; you are calling a non-member function and calling fun is not much different from that.
Further, with a grain of salt your example is not much different from
#include <iostream>
using namespace std;
class demo_class
{
};
void fun2(void)
{
cout<<"i am fun2\n";
}
void fun3(demo_class& dc)
{
cout<<"i am fun\n";
cout<<"i can call fun2\n";
fun2();
}
int main()
{
demo_class ob1;
fun3(ob1);
return 0;
}
A member function can always be transformed into a free function. If fun would access private members we would have to declare it as friend to make the above work, but otherwise no problem here.
You can also do the reverse and call member functions in free functions as in
struct foo {
void bar(){}
};
void func(foo& f) {
f.bar();
}
int main() {
foo f;
func(f);
}

How to pass a function from 1 struct to another function in a different struct using parameter

I'm learning the concept of passing a function as a parameter.
First I've tried pass a "free function?" (function that not belong to any class or struct) to another free function using this pointer void(*Func)(int) and it worked.
Second, a free function to a function belong to a struct using the same pointer, also worked.
But when I tried to pass a function in a struct to another function in a different struct with that same pointer, it prompted error.
Here's my code:
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
using namespace std;
struct A {
void Func_A (void (*Func)(int)) {
(*Func)(5);
}
};
struct B {
void Func_B (int a) {
cout<<a;
}
};
int main () {
A a;
B b;
a.Func_A(b.Func_B);
char key = getch();
return 0;
}
Here the error prompt:
[Error] no matching function for call to 'A::Func_A(<unresolved overloaded function type>)'
To pass a non-static member function around, the syntax is a little different. Here is your original code, reworked to show this:
#include <iostream>
struct B {
void Func_B (int a) {
std::cout << a;
}
};
struct A {
void Func_A (void (B::*Func)(int), B &b) {
(b.*Func) (5);
}
};
int main () {
A a;
B b;
a.Func_A (&B::Func_B, b);
return 0;
}
Note the different function signature for Func_A and the fact that you have to pass an instance of class B when you call it.
Live demo
It's a shame you can't use C++11. std::function makes this a lot simpler and more generalised.
Consider this example:
#include <iostream>
using namespace std;
struct A {
void Func_A (void (*Func)(int)) {
(*Func)(5);
}
};
struct B {
int x;
void Func_B (int a) {
cout << a << " " << x;
}
};
int main () {
A a;
B b1;
b1.x = 1;
B b2;
b2.x = 2;
a.Func_A(b1.Func_B);
return 0;
}
In that example, Func_B uses both the input a and the data member x, so it is clear that the result of a call to Func_B will be different depending on the object, if it is b1 or b2 that is calling it.
You might think that taking the function pointer "b1.Func_B" would clarify that you mean the function associated with the b1 object, but that does not work because the member functions do not exist separately for each instance. The function Func_B only exists once in memory, so it is not possible to have separate function pointers for "b1.Func_B" and "b2.Func_B". So, it cannot work.
The g++ 8.2.0 compiler gives the following error message for the a.Func_A(b1.Func_B); line in the code:
error: invalid use of non-static member function ‘void B::Func_B(int)’
hinting that it would be OK to do such a thing for a static member function. That makes sense, because a static member function cannot make use of the data members of any instance, so it is more like a "free function", not dependent on any instance.

I am unable to initialize a data member of object by passing object as parameter

#include<iostream>
using namespace std;
class one
{
public:
int datam;
void show()
{
cout<<datam;
}
};
void addv(one par)
{
par.datam=2;
}
int main()
{
one w;
addv(w);
w.show();
return 0;
}
After compilation this gives garbage value. Why can't I initialize datamember(datam) of object w.
I know there are other methods to initialize but what is the problem in this method?
You need to pass by reference. See the modified code below:
#include<iostream>
using namespace std;
class one
{
public:
int datam;
void show()
{
cout<<datam;
}
};
void addv(one &par)
{
par.datam=5;
}
int main()
{
one w;
addv(w);
w.show();
return 0;
}
Note that I have changed the prototype of function addv() as:
void addv(one &par)
//------------^^^^
In your code, you are passing by value (and not reference) due to which, you get a garbage value. Working code here.
You are not passing anything by reference. To pass by reference your function should be declared as void addv(one &par) . So you are passing a copy and initializing the copy which gets destroyed before the function returns.

Function "was not declared in this scope"

I'm new to C++ and get a beginner's mistake:
myclass.cpp: In function ‘int main()’:
myclass.cpp: 14:16: error: ‘func’ was not declared in this scope
This is the code:
#include <iostream>
using namespace std;
class MyClass{
public:
int func(int);
};
int MyClass::func(int a){
return a*2;
}
int main(){
cout << func(3);
}
I hope you can help me.
int main(){
cout << func(3);
}
func is not a global function; it is a member function of the class. You need an instance of the class to access it.
For example:
int main()
{
MyClass obj;
std::cout<< obj.func(3);
}
func is a member function, so it must be invoked through an object. For example:
int main()
{
MyClass obj;
std::cout << obj.func(3); // 6
}
In your example, you treated it as a free function, so the compiler looked for a function with that name. Since it could not find it, it issued a compiler error.
func is a member function of MyClass. To call it, you need an object of MyClass type to invoke it on:
int main(){
MyClass m; // Create a MyClass object
cout << m.func(3);
}
Alternatively, you could make func a static member function, which means that it is not associated with any particular instance of the class. However, you would still need to qualify its name as belonging to the MyClass class:
class MyClass{
public:
static int func(int);
};
int MyClass::func(int a){
return a*2;
}
int main(){
cout << MyClass::func(3);
}