#include "stdafx.h"
#include <iostream>
using namespace std;
class thing{
public:
int stuff, stuff1, stuff2;
void thingy(int stuff, int *stuff1){
stuff2=stuff-*stuff1;
}
}
int main(){
thing t;
int *ptr=t.stuff1;
t.thingy(t.stuff, *ptr);
}
I've been practicing classes, and pointers in C++. What i'm trying to do is have the function thingy modify the stuff2 data member in the thing class by passing a pointer to the value of stuff1. How do I go about doing this?
You are creating a variable of type pointer-to-int: if you want a pointer to t.stuff1, take its address:
int* ptr = &t.stuff1;
___^ here you are taking a reference (address)
Then, pass that pointer to your thing::thingy method:
t.thingy(t.stuff, ptr);
__^ don't dereference the pointer, your function takes a pointer
Try this:
int *ptr;
*ptr = t.stuff1;
t.thingy( t.stuff, ptr);
Im probably really late to the party but i wanted to get some good comments and test
//#include "stdafx.h"
#include <iostream>
using namespace std;
//class declaration
class thing{
public:
int stuff, stuff1, stuff2;
thing(){//constructor to set default values
stuff = stuff1 = stuff2 = 10;
}
void thingy(int param1, int *param2){
stuff2=param1-*param2;
}
};
//driver function
int main(){
thing t;//initialize class
cout << t.stuff << ' ' << t.stuff1 << ' ' << t.stuff2 << endl;//confirm default values
int *ptr= &t.stuff1;//set the ADDRESS (&) of stuff1 to an int pointer
cout << *ptr << endl;
t.thingy(t.stuff, ptr); //call function with pointer as variable
cout << t.stuff1;
}
int *ptr=t.stuff1;
you cannot convert int to int*
t.stuff1 is an int value, not a pointer of int
try this:
int *ptr=&t.stuff1;
and you should add ";" at the end of the define of class, like this:
class Thing {
...
};
and when you call t.thingy, the second param is int*
But *ptr is an int value, not a pointer. ptr is a pointer, not *ptr. try this:
t.thingy(t.stuff, ptr);
you should know:
int i_value = 1;
int* p_i = &i_value;
int j_value = *p_i;
in this case:
the type of i_value j_value *p_i is int
the type of p_i is int*
You should pass the address:
*ptr = &(t.stuff1);
Related
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 1 year ago.
i'm code beginner
#include <bits/stdc++.h>
using namespace std;
void init(int* arr){
arr = new int[10];
cout << arr << endl;
}
int main(int argc, char* argv[]){
int *arr;
init(arr);
cout << arr << endl;
}
this is a simple code.
My question is that why arr's address in init function and arr's address in main function is different?
My think is that i gave arr's address to init function and in init function, arr is assigned a new address through 'new int[10]'
So, arr's address in init function and in main will be same.
but this code doesn't work as i think.....
Can you tell me why?
Step back a little and think about how arguments are passed into functions.
void foo(int x) {
}
int main() {
int x;
foo(x);
}
Here the x in main() is actually passed by value to foo() which means a copy of x is created when passing to foo().
With the same logic, if you think of int * as another variable type
using intPtr = int*; //a sort of typedef
void foo(intPtr x) {
}
int main() {
intPtr x;
foo(x);
}
a copy of x is again created. This is what is happening in your program. For what you expect, you need to pass in the variable by reference
using intPtr = int*;
void foo(intPtr& x) {
}
int main() {
intPtr x;
foo(x);
}
Adapting the same to your program:
#include <iostream>
void init(int*& arr){
arr = new int[10];
std::cout << arr << '\n';
}
int main(int argc, char* argv[]){
int *arr;
init(arr);
std::cout << arr << '\n';
delete(arr);
}
There's another way with pointers that is using a pointer to a pointer (**)
#include <iostream>
void init(int** parr){
*parr = new int[10];
std::cout << *parr << '\n';
}
int main(int argc, char* argv[]){
int *arr;
init(&arr);
std::cout << arr << '\n';
delete(arr);
}
where the address of arr (&arr) is passed into the function. Inside the function, the contents of parr is modified (which is arr in this case).
#include<iostream>
using namespace std;
class Test
{
private:
int x;
public:
Test(int x = 0) { this->x = x; }
void change(Test *t)
{
this = t; //line 1
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj(5);
Test *ptr = new Test (10);
obj.change(ptr);
obj.print();
return 0;
}
since we know that this pointer hold the reference of calling object. In line 1 i am trying to change the reference of calling object but it shows an error "lvalue required". Can someone explain this??
You cannot assign a pointer to this pointer, because it's a prvalue.
this pointer is a constant pointer that holds the memory address of the current object.
As a result, this is of type const Test* in your case, so it cannot be assigned to. Doing so (if it was allowed) would effectively allow an object to change its own address in memory, as #Peter mentioned.
Note: const Test* is a pointer to a constant object. The object it points to is constant, not the pointer itself.
PS: this->x = t->x; is probably what you meant to say.
Here you are assigning a pointer(here t) to "this" pointer for a particular object.
"this" pointer is const. pointer that holds the memory address of the current object. You simply can't change the this pointer for an object, since doing this you will practically be changing the location of the object in the memory keeping the name same.
Reference - ‘this’ pointer in C++
#include <iostream>
using namespace std;
class Test
{
private:
int x;
public:
Test(int x=0)
{
this->x = x;
}
void change(Test *t)
{
t->x; //t is a pointer. so make it point to x
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj(5);
Test obj1(10); //create a new object
Test *ptr = &obj1;//make the pointer point to obj1
obj.change(ptr); //use change() to point to argument of obj1
obj.print(); //print the value of obj now
return 0;
}
I try to create a vector with a pointer (so that everything is stored in/on the heap). I then want to fill the vector with an array of a class. I am thinking about accessing the class by class[i].member... Sadly, it does not work.
If I try this without a vector it works, like in:
tClass *MyClass = new tClass[5]
I am trying this without a specific purpose and only to understand C++ better. Can anyone have a look where I am wrong? Thanks!
Here is the code:
#include "iostream"
#include "vector"
using namespace std;
class tClass
{
private:
int x = 0;
public:
int y = 0;
tClass(){cout << "New" << endl;};
~tClass(){}; //do I need to make a delete here?
int main ()
{
vector<tClass> *MyClass[5];
MyClass = new vector<tClass>[5];
cout << MyClass[3].y << endl;
delete[] MyClass;
}
as others have suggested if you want just a vector of tClass you would do the following
vector<tClass> vectorName (5);
and access it like so
vectorName[3].y;
however if you wanted a vector of tClass pointers you would initialise and acess it like this
vector<tClass*> vectorName(5);
vectorName[3]->y;
edit
this might help you a bit more, this is your code, with comment to help you understand what is going wrong
class tClass
{
private:
int x = 0;
public:
int y = 0;
tClass(){ cout << "New" << endl; };
~tClass(){}; //do I need to make a delete here? //no you dont need to make a delete here as this class contains no "news"
int main()
{
vector<tClass> *MyClass[5]; //use () to give a vector an initial size, [] is only to access a member
//also to have a vector holding pointers, the asterisk needs to be after tClass not before the vector name
MyClass = new vector<tClass>[5];
cout << MyClass[3].y << endl; //discused above
delete[] MyClass; //only needed if a new is used, however you dont need one here, as it will just go out of scope
}
here is you code, but fixed to compile and run with the use of pointers
#include <iostream>
#include <vector>
using namespace std;
class tClass
{
private:
int x = 0;
public:
int y = 0;
tClass(){ cout << "New" << endl; };
};
int main()
{
vector<tClass*> MyClass(5);
cout << MyClass[3]->y << endl;
}
note though that this will give an error as the vector of class pointers are not pointing to any class
If have a class:
class classA {
public:
int z = 5;
};
I understand RAII to be when I write classA Aobject but what do I do if I want to declare a global pointer?
classA *Aobject;
int main()
{
Aobject = new classA; //not RAII
cout << Aobject->z << endl;
return 1;
}
I assume that what you mean is you want to declare an object, but you don't want to initialize it right away, perhaps because you don't have all the parameters you need in order to construct it properly yet. Is that correct? Use a smart pointer.
#include <memory>
#include <iostream>
std::unique_ptr<classA> Aobject;
int main()
{
Aobject.reset(new classA);
cout << Aobject->z << endl;
return 1;
}
I am trying to transfer a function as a parameter to a different function.
for some reason it is not working.
//myClass.h
class MyClass
{
public:
typedef int (*MyClass::ptrToMember)(float, char);
ptrToMember p1;
MyClass::MyClass();
void hello(ptrToMember fun);
int SendIt (float a, char b);
};
//MyClass.cpp
MyClass::MyClass(){
p1 = &(MyClass::SendIt);
hello(p1);
}
int MyClass::SendIt (float a, char b)
{
std::cout << "MyClass::SendIt "<<a<<std::endl;
return 1;
}
void MyClass::hello(ptrToMember fun){
int result = (*fun)(12, 'a');
std::cout << result << std::endl;
}
would appreciate it, if someone can tell me what my mistake is.
typedef int (*MyClass::ptrToMember)(float, char);
^
// your mistake is here
Pointers to class member functions are declared like this:
typedef int (MyClass::*ptrToMember)(float, char);
^
And called like this (test is the class instance - can also be 'this'):
(test.*pointer)(parameters) // if test is automatically allocated
or
(test->*pointer)(parameters) // if test is a pointer
The decleration operator is ::*, while the operator to invoke your pointer to a member function are .* and ->*.
Edit:
This line:
p1 = &(MyClass::SendIt);
actually has to be:
p1 = &MyClass::SendIt; // without parentheses
Say this:
typedef int (MyClass::*ptrToMember)(float, char);
// ...
int result = (this->*fun)(12, 'a');