learning C++

Thread Starter

PG1995

Joined Apr 15, 2011
832
Hi

I wanted to know if I can ask C++ related questions here. I'm trying to learn C++ and can write simple codes. But many a time the compiler give many errors which I'm unable to fix myself. It would be very helpful if someone well versed in C++ can help me with the coding. Thanks.

Regards
PG
 

DumboFixer

Joined Feb 10, 2009
217
As it's in Programmers Corner I don't see why you can't ask :)

There are C++ programmers here (myself included) who'll try and point you in the right direction.
 

HunterDX77M

Joined Sep 28, 2011
104
Hi

I wanted to know if I can ask C++ related questions here. I'm trying to learn C++ and can write simple codes. But many a time the compiler give many errors which I'm unable to fix myself. It would be very helpful if someone well versed in C++ can help me with the coding. Thanks.

Regards
PG
We'll do our best to help. If you are just starting out learning the language, might I recommend C++ for Dummies from Wiley Publishing? It sounds juvenile, but is a great resource. Highly recommended.
 

Thread Starter

PG1995

Joined Apr 15, 2011
832
Thanks a lot, Dumbo, Hunter.

I have a book so I have some basic knowledge of the workings of C++. Anyway, thanks for the recommendation of the book, Hunter.

Let's start here. The code below is giving me a lot of trouble and I'm at end of my wits. I'm trying to learn the concept of class within a class etc. I use Code:Blocks. It would really nice of you if you can fix it. It needs some edits.

Rich (BB code):
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

//***********************************************************
class Student
{
    private:
        string name; //John
        int rollNumber;

    private:
        class Date
        {
            public:
                int day;
                string month; // Jan, Feb
                int year;

                public:
                    void readDate();
                    Date(int dummyDay, string dummyMonth, int dummyYear) : day(dummyDay),
                    month(dummyMonth), year(dummyYear)
                    { }
        };


    public:
        void readStudent();
        void printStudent();

};
//************************************************************************


int main()
{
    Student student;
    Date date;

    student.readStudent();
    student.printStudent();

    system("pause");
    return 0;
}

//************************************************************

void Student::readStudent()
{
    Student student;

    cout << "enter name: "; cin >> name;
    cout << "enter roll no.: "; cin >> rollNumber;
    readDate();
    Date(int day, string month, int year);
}

//***********************************************************

void Student::printStudent()
{
    cout << "name: " << name << endl;
    cout << "roll number: " << rollNumber << endl;
    cout << "date of birth: " << date.day << "" << date.month << "" << date.year << endl;
}

//************************************************************

void Student::Date::readDate()
{
    int day; string month; int year;

    cout << "enter day: "; cin >> day;
    cout << "enter month: "; cin >> month;
    cout << "enter year: "; cin >> year;
}
Errors List:

Rich (BB code):
In function 'int main()':|
41|error: 'Date' was not declared in this scope|
41|error: expected ';' before 'date'|
In member function 'void Student::readStudent()':|
58|error: 'readDate' was not declared in this scope|
59|error: expected primary-expression before '(' token|
59|error: expected primary-expression before 'int'|
59|error: expected primary-expression before 'month'|
59|error: expected primary-expression before 'int'|
In member function 'void Student::printStudent()':|
68|error: 'date' was not declared in this scope|
||=== Build finished: 8 errors, 0 warnings ===|
 
Last edited:

DumboFixer

Joined Feb 10, 2009
217
right, lets go one step at a time.

in the function main you have the line
Rich (BB code):
Date date;
which the compiler objects to. It does this because Date is defined as private within Student and is therefore only accessable from within Student. Try sorting that out may as it may help elsewhere.

When calling Date in readstudent did you mean date ? Also you don't need to specify the "int" as the variables have already been declared, you are just passing their values.

A comment I'd make (and it's not right or wrong) is about coding style.

When declaring a class I'd started the class name with C. For example
Rich (BB code):
class CStudent
	
	
	
	



	



	










Rich (BB code):
That way there's less chance of confusion. Compare the following 2 lines

	
	
	
	



	



	










Rich (BB code):
class CStudent
class Student
start a class definition. Now when you come to declare a variable of each type you have
Rich (BB code):
CStudent student1
Student student
That way it's obvious that there's no typo between the upper and lower case "S". Also I'd stay clear of using variable names that could be confused with reserved names. You could try starting class variables with "m" to show that they are member variables. If you are just learning C++ then I'd stay clear of doing things like class definitions within another class. Start with simple class definitions and expand your understanding from there.
 

debjit625

Joined Apr 17, 2010
790
You have to learn about access specifiers,their are 3 access specifiers in C++ 1)Private, 2)Public and 3)Protected.In Student class you have declared the Date class as private which means you can only access Date class from inside Student class or its member functions.So when you define Date inside main function you get these errors
In function 'int main()':|
41|error: 'Date' was not declared in this scope|
41|error: expected ';' before 'date'|
Inside readStudent() function why you have defined a Student class I have no idea why you did that..

Inside readStudent() function you have called readDate() function,you can't call a function like that you need an object to call that function as its a member function of Date class.So you get this error
58|error: 'readDate' was not declared in this scope|
Date(int day, string month, int year);
What is it for?? I have no idea.....if you want to define an object, its not the way.For this you get these errors
59|error: expected primary-expression before '(' token|
59|error: expected primary-expression before 'int'|
59|error: expected primary-expression before 'month'|
59|error: expected primary-expression before 'int'|
cout << "date of birth: " << date.day << "" << date.month << "" << date.year << endl;
Inside printStudent() you have used object "date",you cant do that it was declared and defined inside main function scope, with out passing it as a parameter to printStudent() function you cant use that date object as it was declared inside main's scope, its name is not visible outside main.So you get this error
68|error: 'date' was not declared in this scope|
Anyway I have no idea how much you know about C++ but as you asked to edit your code I am doing it,but always go with your own logic.Here I have used reference to pass the objects,you can use pointers but reference looks good and in some case it is better to pass objects with them.As per your logic Date needs constructor call but you can also use default constructors to avoid them...

Rich (BB code):
#include<iostream>
#include<cstdlib>
#include<string>
usingnamespace std;
//***********************************************************
class Student
{
private:
string name; //John
int rollNumber;
 
 
public:
class Date
{
public:
int day;
string month; // Jan, Feb
int year;
public:
void readDate();
Date(int dummyDay, string dummyMonth, int dummyYear) : day(dummyDay),
month(dummyMonth), year(dummyYear)
{ }
};
 
public:
void readStudent(Date& date);
void printStudent(Date& date);
};
//************************************************************************
 
int main()
{
Student student;
Student::Date date(1,"Jan",1989);
student.readStudent(date);
student.printStudent(date);
system("pause");
return 0;
}
//************************************************************
void Student::readStudent(Date& date)
{
Student student;
cout << "enter name: ";
cin >> name;
cout << "enter roll no.: ";
cin >> rollNumber;
date.readDate();
}
//***********************************************************
void Student::printStudent(Date& date)
{
cout << "name: " << name << endl;
cout << "roll number: " << rollNumber << endl;
cout << "date of birth: " << date.day << " / " << date.month << " / " << date.year << endl;
}
//************************************************************
void Student::Date::readDate()
{
cout << "enter day: "; cin >> day;
cout << "enter month: "; cin >> month;
cout << "enter year: "; cin >> year;
}
Good Luck
 

debjit625

Joined Apr 17, 2010
790
For pc work I try to steer clear of C++.
Visual C# express is much easier to learn and debug.
Its free and very powerful.

Me too, but not powerful like C/C++.C# use .Net its an intermediate language program i.e.. it will target CLR(.Net runtime).C# programs will only run under platform which can run .Net runtime. In case of embedded system programmers they should learn C/C++ or any language which can be compiled or assembled to native code.

Anyway I like C# very much, and for fast development and for prototype applications I use it all the time.

I use VisualStudio C++ Express Edition more than CodeBlock with gcc.But both are good and both are free.
 

Thread Starter

PG1995

Joined Apr 15, 2011
832
Thank you, Dumbo, Debjit.

@Dumbo: Your suggestions proved very useful. The next time I write a code I will implement your suggested coding style.

@Debjit: Your edited code proved to be very helpful as it gave me an opportunity to play around with the working code and I learned many things.

I would request you to have a look on the two codes below. They are both working fine. Please do have a look on the comments. Let me know of any suggestions you have. It would better if you copy those codes in your compiler.

CODE 1:
Rich (BB code):
// learning_nested_classes.cpp
// this program demonstrates how the concept of classes and objects work

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

///////////////////////////////////////////////////////////
class Student
{
    private:
        string name; //John
        int rollNumber;


    public:
        class Date
        {
                private:
                    int day;
                    string month; // Jan, Feb
                    int year;

                public:
                    void readDate();
                    void printDate();

                    Date()
                    { } //you also need to have the default when there is a created one as the one below
                    Date(int dummyDay, string dummyMonth, int dummyYear) : day(dummyDay),
                    month(dummyMonth), year(dummyYear)
                    { }
        };

    public:
        void readStudent();
        /* void readStudent(Date& date); you simple readDate() because date members of Date class       are private */
        void printStudent(Date& date);
};
///////////////////////////////////////////////////////////

Student::Date date;// "::" is called scope resolution operator

int main()
{
Student student;
//Student::Date date(1,"Jan",1989); you don't wanna do this because you can input the date
//Student::Date date; made this global
student.readStudent();
student.printStudent(date);
cout << endl << endl;

system("pause");
return 0;
}
//---------------------------------------------------------

void Student::readStudent()
{
//Student student; you do not need to define any variable
cout << "enter name: "; getline(cin, name);
cout << "enter roll no.: "; cin >> rollNumber;
date.readDate();
}
//---------------------------------------------------------

void Student::printStudent(Date& date)
{
cout << "name: " << name << endl;
cout << "roll number: " << rollNumber << endl;
/* cout << "date of birth: " << date.day << "/" << date.month << "/" << date.year << endl;
to execute this you need to make data members of Date class public */
date.printDate(); // if data members of Date class are private, use this
}
//---------------------------------------------------------

void Student::Date::readDate()
{
cout << "enter day: "; cin >> day;
cout << "enter month: "; cin >> month;
cout << "enter year: "; cin >> year;
}
//---------------------------------------------------------

void Student::Date::printDate()
{
    cout << "date of birth: " << date.day << ":" << date.month << ":" << date.year << endl;
}
//---------------------------------------------------------
CODE 2:
Rich (BB code):
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

///////////////////////////////////////////////////////////
class Student
{
    private:
        string name; //John Andrews
        int rollNumber;

    public://if you make this private you won't be able to access it thru simple means as far as I know
        class Date
        {
            private:
                int day;
                string month; // Jan, Feb
                int year;

            public:
                void readDate();
                void printDate();

                //Date()
                //{ }
                Date(): day(0), month("Jan"), year(0)// to use this constructor get rid the above
                { }
                Date(int dummyDay, string dummyMonth, int dummyYear): day(dummyDay),
                month(dummyMonth), year(dummyYear)
                { }
        };

    public:
        void readStudent();
        void printStudent();

};
///////////////////////////////////////////////////////////

Student::Date date (23, "Jan", 2000);

int main()
{
    Student student;

    student.readStudent();
    student.printStudent();

    cout << endl << endl;

    system("pause");
    return 0;
}
//---------------------------------------------------------

void Student::readStudent()
{
    cout << "enter name: "; getline(cin, name);
    cout << "enter roll no.: "; cin >> rollNumber;
    date.readDate();
}
//---------------------------------------------------------

void Student::printStudent()
{
    cout << "name: " << name << endl;
    cout << "roll number: " << rollNumber << endl;
    date.printDate();
}
//---------------------------------------------------------

void Student::Date::readDate()
{
    cout << "enter day: "; cin >> day;
    cout << "enter month: "; cin >> month;
    cout << "enter year: "; cin >> year;
}
//---------------------------------------------------------

void Student::Date::printDate()
{
    cout << date.day << ": " << date.month << ": " << date.year << endl;
}
//---------------------------------------------------------
 

debjit625

Joined Apr 17, 2010
790
Not much to say both are working fine, and as you are starting with C++ its good that you found two different ways to do it. But in real life you would be using reference or pointers and making the Date class as private, and its what for we use OOP(encapsulation).

In the first code you have used default constructor ,but that will not initialize the Date class data members like (day,month,year) when an object of Data class will be created. Which is bad practice. C++ sets some rules for OOP,you can bypass them but a good programmer will avoid that...in C++ class constructors are for initialization of data members i.e.. it guarantee the programmer that whenever an instance of Data class will be created the data members(day,month,year) will be initialized to avoid any kind of error.

In second code you used global object for Date class,doing that you bound the functions like
Rich (BB code):
student.readStudent();
student.printStudent();
to that date object,any other instance of date object can't be used so its really miss use of OOP.

But again for the first time its too good,that's how we learn...

Here is a trick,C++ provides a tool called default arguments in class constructors you can use it,here is an example.
Rich (BB code):

#include <iostream>

#include <string>
using namespace std;
class mcu
{
private:
string id;
int size;
int cost;
public:
//Constructor with default arguments...
mcu(string s_id = "PIC18F4520",
int i_size = 8,int i_cost = 200):id(s_id),size(i_size),cost(i_cost)
{}
void print()
{
cout<<"Microcontroller Size Cost\n";
cout<<id<<" "<<size<<" "<<cost<<endl;
}
};

int main()
{
mcu m;
//mcu m("PIC16F877A",8,120); //Uncomment this 
//and comment the above to check the effect
m.print();
system("pause");
return 0;
}
One more thing you are using "cstdlib" ,in your code its not needed.

Good Luck
 

Thread Starter

PG1995

Joined Apr 15, 2011
832
Thank you, Debjit. Actually I also wanted to show that your code helped me to clear me of many of the confusions because I had something beforehand which was working and played with it around. Thank you very much. I would need your help in future so please be there! :)

Best wishes
PG
 
Last edited:

Thread Starter

PG1995

Joined Apr 15, 2011
832
Hi

The class Date is a private member class of class Student. That means it would be accessible to the class Student but not to something from outside without first resorting to the main class first etc.

Although readDate() and printDate() functions are public but I believe now they also won't be accessible because you have 'locked'/'sealed' the main entrance. Correct? Please let me know.

Is there any simple way (I mean which a beginner like me can use) to use private class Date?

I have also tried to create a structure structDate inside the class Student. Will it work? So far, it isn't? Is creating a structure inside a class allowed?

Please help me with the queries above. Thank you.

Regards
PG


Rich (BB code):
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

///////////////////////////////////////////////////////////
class Student
{
    private:
        string name; //John
        int rollNumber;


    private://trying to make this class private and see what happens?
        class Date
        {
                private:
                    int day;
                    string month; // Jan, Feb
                    int year;

                public:
                    void readDate();
                    void printDate();

                    Date()
                    { } //you also need to have the default when there is a created one as the one below
                    Date(int dummyDay, string dummyMonth, int dummyYear) : day(dummyDay),
                    month(dummyMonth), year(dummyYear)
                    { }
        };

    public:
        void readStudent();
        /* void readStudent(Date& date); you use simple readDate() because date members of Date class   are private */
        void printStudent(Date& date);

        struct structDate = {int day; string month; int year;};// would it work?
};
///////////////////////////////////////////////////////////

Student::Date date;// "::" is called scope resolution operator
// if you don't make it global then you would need to pass the date as argument in member functions of // class Student

int main()
{
Student student;
//Student::Date date(1,"Jan",1989); you don't wanna do this because you can input the date
//Student::Date date; made this global
student.readStudent();
student.printStudent(date);
cout << endl << endl;

system("pause");
return 0;
}
//---------------------------------------------------------

void Student::readStudent()
{
//Student student; you do not need to define any variable
cout << "enter name: "; getline(cin, name);
cout << "enter roll no.: "; cin >> rollNumber;
date.readDate();
}
//---------------------------------------------------------

void Student::printStudent(Date& date)
{
cout << "name: " << name << endl;
cout << "roll number: " << rollNumber << endl;
/* cout << "date of birth: " << date.day << "/" << date.month << "/" << date.year << endl;
to execute this you need to make data members of Date class public */
date.printDate(); // if data members of Date class are private, use this
}
//---------------------------------------------------------

void Student::Date::readDate()
{
cout << "enter day: "; cin >> day;
cout << "enter month: "; cin >> month;
cout << "enter year: "; cin >> year;
}
//---------------------------------------------------------

void Student::Date::printDate()
{
    cout << "date of birth: " << date.day << ":" << date.month << ":" << date.year << endl;
}
//---------------------------------------------------------
Errors:
Rich (BB code):
42|error: expected unqualified-id before '=' token|
20|error: 'class Student::Date' is private|
46|error: within this context|
||=== Build finished: 3 errors, 0 warnings ===|
 

debjit625

Joined Apr 17, 2010
790
Although readDate() and printDate() functions are public but I believe now they also won't be accessible because you have 'locked'/'sealed' the main entrance. Correct? Please let me know.
Yes.
Is creating a structure inside a class allowed?
Yes.
As C is a structural programming language,structures are used in C.C is not an Object Oriented Programming (OOP) Language,so C++ was developed to have every thing of C plus OOP and classes was the tool by which we create object in C++.You can think C as a sub set of C++.So you can create structures inside classes and many times its too usefull.In C++ a structure will behave just like class,just one difference if you create any data member or function inside class it will be private and in case of structure it will be public.To change that you have to use access specifiers.

Your code didn't worked because your structure declaration is not correct,it should be like this
Rich (BB code):

struct structDate 
{
int day; 
string month; 
int year;
};// would it work?

And your Date class is private you can't access it,so you can't make a global object of Date.

Is there any simple way (I mean which a beginner like me can use) to use private class Date?
May this one is simple...
Rich (BB code):

#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string name; 
int rollNumber;
class Date
{
public:
int day;
string month;
int year;

void readDate();
void printDate();
Date(int dummyDay, string dummyMonth, int dummyYear) : day(dummyDay),
month(dummyMonth), year(dummyYear)
{ }
};
Date date;//Create a private instance of Date and use
//it inside Student class and its member functions
public:
//Use Student's constructor to initialize Date's data members
Student(int dummyDay, string dummyMonth, int dummyYear):date(dummyDay,dummyMonth,dummyYear)
{
}
void readStudent();
void printStudent();
};

int main()
{
Student student(0,"NULL",0);
student.readStudent();
student.printStudent();
cout << endl << endl;
system("pause");
return 0;
}

void Student::readStudent()
{
cout << "enter name: "; getline(cin, name);
cout << "enter roll no.: "; cin >> rollNumber;
date.readDate();
}

void Student::printStudent()
{
cout << "name: " << name << endl;
cout << "roll number: " << rollNumber << endl;
date.printDate();
}

void Student::Date::readDate()
{
cout << "enter day: "; cin >> day;
cout << "enter month: "; cin >> month;
cout << "enter year: "; cin >> year;
}

void Student::Date::printDate()
{
cout << "date of birth: " << day << ":" <<month << ":" << year << endl;
}
I would need your help in future so please be there!
We all are here for that....

Good Luck
 

TheFox

Joined Apr 29, 2009
66
Infact,
Rich (BB code):
struct Alpha
{
int A;
};
class Beta
{
public:
int B;
}
Are the same. Stucts are public by default, and classes are private.
 
Top