0
Can objects also be treated as variables in c++ and why?
5 Answers
+ 3
Your question is unclear to me. Is it your homework? Could you provide some context and an example code?
+ 1
If you try to change the value of testValue outside of main, you get the same error.
https://code.sololearn.com/czr4CcpDj8aP/?ref=app
It doesn't matter if it is an integer or a Student variable.
0
I think this might help derive meaning from my question.
Classes are user defined data types which can just be liken to a variable declared with a primitive data type. The variable declared with a primitive data type can be made globally to be accessed by any function right,
So this is now my question,
If objects are instances of a class, can they also be treated as a variable ?
If they are then why can't they be accessed by any function when declared global.
From the example code below, I have an object from the student class but I can't access it in an function. Therefore based on this, I want to know if objects are also variables?
Example
#include <iostream>
using std::cout;
class Student{
int marks[ 10 ];
string name;
string subjects [ 10 ];
void Grade( );
} ;
int testValue = 6;
Student s1;
s1.name = " Abban Justice";
int main( ){
/* here the s1 object can't be accessed by main function but variable testValue can be accessed */
cout<<s1.name<<endl;
cout<<testValue;
return 0;
}
0
Okay thanks
0
You can access the objects like any other variable, the problem in your case would be that you are trying to access a private member.
Members of a class are private by default, you have to explicitly specify if you want them public.