Reputation: 646
So I was practicing OOPS and was trying to understand private and public.For this I created a different file in sources folder of my project(btw I am using Code::Blocks) like this:
+--Sources
+--main.cpp
+--student.cpp
main.cpp :
#include <iostream>
#include "student.cpp"
using namespace std;
int main(){
Student s1;
s1.age = 20;
s1.rollNo = 101;
s1.display();
}
student.cpp :
class Student{
public:
int rollNo;
private:
int age;
public:
void display(){
cout << age << " " << rollNo << endl;
}
};
Edited student.cpp :
#include <iostream>
class Student{
public:
int rollNo;
private:
int age;
public:
void display(){
std::cout << age << " " << rollNo << std::endl;
}
};
And this is giving me the following errors:
error: 'endl' was not declared in this scope
error: 'cout' was not declared in this scope
error: 'int Student::age' is private within this context
From what I understand,first two errors are due to the student.cpp not recognizing iostream headers.Is there different way to work with classes in code::blocks and if not what else can I use?
Also why am I getting third error,since I am trying to access age
using a different function(display
) which is public inside the Student
class?
Upvotes: 0
Views: 105
Reputation: 16310
There are too many issues with the organization of this code that lead you to the problem. Here it is a list of things to fix:
using namespace std;
(outside a well defined scope). Using it "globally" (like you did) breaks encapsulation (in some sense) by changing the meaning of code far away. The puzzling behavior is only one of the consequences.cpp
files are never #include
d. cpp
s are for implementation and hpp
s are for declaration (and maybe some implementation).student.cpp
file should be a student.hpp
reallystudent.hpp
should have its own "header" dependencies (#include<iostream>
in student.hpp
)std::cout
and std::endl
, or using std::cout; using std::endl;
(at worst using namespace std
) but locally.All above is about style and conventions. Besides that you have syntax error:
age
should be public according to the desired usage in main
.Ideally your code should look like this (not tested):
+--Sources
+--main.cpp
+--student.hpp
main.cpp :
#include "student.hpp"
using namespace std;
int main(){
Student s1;
s1.age = 20;
s1.rollNo = 101;
s1.display();
}
student.hpp :
#include <iostream>
class Student{
public:
int rollNo;
int age;
private:
// was int age
public:
void display(){
using std::cout;
cout<< age <<" "<< rollNo <<'\n'; // no need for endl
}
};
student.cpp is not needed or might be empty.
Upvotes: 6