Jump to content



Welcome to AstaHost - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!

Toggle shoutbox Shoutbox Open the Shoutbox in a popup

@  yordan : (21 April 2014 - 09:11 PM) Hey, Ritesh, Did You Hear Me?
@  yordan : (14 April 2014 - 05:28 PM) By The Way, This Could Be An Interesting Subject For A Topic, What About Posting This Question? Let's See If Other People Have The Same Feeling Concerning Bootlists!
@  yordan : (13 April 2014 - 09:36 AM) Boot Order : Cd, [Usb,] Hard Drive :D
@  yordan : (11 April 2014 - 07:23 PM) I Simply Let The Bios Do That
@  Ritesh : (11 April 2014 - 10:23 AM) Is It Possible To Launch Fedora Live Cd Or Installation Disk From Hard Drive On Windows Platform Using Grub Mbr File.
@  Ritesh : (11 April 2014 - 10:21 AM) No U Are Not.. Btw.. I Have Question For You.
@  yordan : (10 April 2014 - 08:02 AM) You Are Partially Right.
I Was Not.
Nevertheless, I Am Again :)
@  Ritesh : (09 April 2014 - 07:33 PM) :P
@  Ritesh : (09 April 2014 - 07:33 PM) I Think U R Not..
@  yordan : (09 April 2014 - 09:28 AM) I'm The Master Of The Shoutbox!
@  yordan : (05 April 2014 - 10:32 PM) He-He
@  Ritesh : (04 April 2014 - 06:59 PM) Ha Ha Ha ....
@  yordan : (04 April 2014 - 11:15 AM) Welcome Back, Starscream!
@  yordan : (03 April 2014 - 02:31 PM) And I Hope That He Will Come Back Soon :)
@  yordan : (01 April 2014 - 02:53 PM) Nice, Ritesh Came, I'm Not Home Alone Today.
@  Ritesh : (01 April 2014 - 08:51 AM) Oh!!! Poor Dear Yordan..
@  yordan : (31 March 2014 - 10:02 AM) I'm A Poor Lonesome Cow-Boy
@  yordan : (27 March 2014 - 02:22 PM) He Is Unpatient Due To His Patients!
@  Ritesh : (27 March 2014 - 10:46 AM) :(
@  Ritesh : (27 March 2014 - 10:46 AM) He Is Busy With His Patients.

Photo
- - - - -

C++: Basic Classes classes, objects, access labels, members, inline functions


10 replies to this topic

#1 bluefish

bluefish

    Member [ Level 2 ]

  • Members
  • 71 posts

Posted 07 January 2007 - 11:19 PM

This tutorial assumes that you have a basic knowledge of C++.

You know how to use built-in types, like ints, doubles, chars, etc. You should know some types that are part of the STL, like vector, etc.

Those types that come in the STL are just C++; you can create your own types just like those! Non built-in types are referred to as classes. To create a class, you just use the keyword class, the name of the class, and curly brackets.

//A class named MyClass
class MyClass {
};

In fact, that is all we need to create variables, pointers, or references to that class.

MyClass a;
MyClass *b = &a;
MyClass &c = a;

The variable "a" is an object of type MyClass.

Of course, something like that hardly does anything. We need to create members of that class - ways it can be created (called constructors), operations that we can perform on it (called member functions), and data it can hold (called data members).

Data Members
I'll start with data members, because you often need them to use constructors and member functions.
A data member is a piece of data, the same as you use normally. It can be a built-in type, or another class type (i.e. vector). A class can have as many data members as you want or need. To declare a data member, simply put the declaration in the body of the class as follows:

#include <vector>

class MyClass {
int i;
std::vector<int> v;
};

So MyClass has two data members: i and v. Normal rules apply. You can also use pointers and references as usual.
- An important thing to note is that i and v are uninitialized. We'll talk about initializing data members later.
- Also, each object of type MyClass has its own different data. The data is referred to by the same name, but each object of type MyClass has its own value for i and v.

Access Control
Before we move on, I would like to discuss access control. There are three main types of access control in a class.
public: Any part of the program can access it
private: Only members of the class can access it
protected: Private except inherited classes can access it NOT COVERED

To change access control, just use the name followed by a colon, and that will be the access control from then on. The default access control is private. You can bypass this by using the struct keyword instead of class - the default access control is then public.

#include <vector>

class MyClass {
int i; //Default is private
public:
int integer; //Public
private:
vector v; //Private
protected:
vector vec; //Protected
};

struct MyClass2 {
int i; //Public, as default
private:
int i2; //Private
};

- A common mistake is to assume that struct has a deeper meaning. It doesn't. It's the exact same as using class and following it with "public:".
- To access a public member of a class, use ObjectName.MemberName. So, using the above example:
MyClass c;
c.integer = 10; //Value of integer is changed
c.i = 10; //Error: private member cannot be accessed

Constructors
Usually, we need to do something when a class is created. We also often need to have different ways to create objects of the same type. That is why we have constructors.

A constructor looks a bit like a function, with a few key differences. For one, it has no return value. Its name must be the same as the class name. For example:

#include <vector>

class MyClass {
public:
MyClass() {
//Constructor
i = 10;
v.push_back(i);
}
int i;
std::vector<int> v;
};

As you can see, you can do anything you want with your data members in the constructor. So now, when we create an object like the following, the operations in the default constructor are called. The default constructor is a constructor with no arguments, and it is called whenever an object of that type is created.
MyClass my;
Since my is initialized with the default constructor, i should now have a value of 10 and v should have one element with a value of 10.

Also, constructors can take values like a normal function.

#include <vector>

class MyClass {
public:
//Default constructor
MyClass() {
i = 10;
v.push_back(i);
}
//Constructor that takes an argument
MyClass(int i2) {
i = i2;
v.push_back(i);
}
int i;
std::vector<int> v;
};

//...

MyClass a; //Initializes with default constructor
MyClass b(); //Initializes with default constructor
MyClass c(4); //Initializes with second constructor

Another important concept is an initializer list. With the above method, your compiler automatically initializes all the data members to their default value, then executes the body of the constructor. This is normally not a big deal, but if you have big classes where initializing them takes a lot of resources, it can be important to do it only once. That is why initializer lists are provided. You can change the default initialization, with the following as an example.

#include <vector>

class MyClass {
public:
//Default constructor
MyClass() : i(10), v(7,2) { //Initialize i with a value of 10; v is initialized with 2 elements with a value of 7
v.push_back(i);
}
//Constructor that takes an argument
MyClass(int i2) : i(i2) { //Initialize i with the argument i2
v.push_back(i);
}
int i;
std::vector<int> v;
};

To create the initializer list, follow the argument list with a colon, then initialize each data member with whatever values. Multiple initializations are seperated by commas. When you use the initializer lists, you can ensure that the data members are initialized only once.

- If you do not provide a default constructor, your compiler will synthesize one for you. This constructor does nothing except initialize all the data members to their default values.
- If your default constructor is private, objects must be created with another constructor - if there are no public constructors, objects of that type cannot be created. Note that the synthesized constructor is public.

Member Functions
A member function is an operation that can be performed on an object. You can declare member functions in the same way as normal functions, except within the body of the class. Member functions can use data members and can call other member functions. They cannot call constructors, but constructors can call them.
You can use access control for member functions. Public functions can be performed as Object.Function(args). Private (or protected) member functions can only be called by other members.

#include <vector>

class MyClass {
public:
void setI(int i2) { i = i2; }
int getI() { return i; }
void multiplyBy6() { doubleI(); tripleI(); }
private:
void doubleI() { i *= 2; }
void tripleI() { i *= 3; }
int i;
};

//...

MyClass m;
m.setI(10);
int i = m.getI(); //i==10
m.multiplyBy6(); //i==60
m.doubleI(); //Error: can't access private member function

The body of a member function does not need to be defined inside the class. It can be defined outside, by declaring it inside and using the scope operator (double colon).

class MyClass {
public:
int getI();
int i;
};

int MyClass::getI() {
return i;
}

This operates the same as getI in the previous example, with one difference.

Inline Functions
An inline function is a function that is actually changed into the appropriate code by the compiler. With short functions, this can increase run-time efficiency. Member functions that are defined within a class are inline by default. Member functions defined outside the class and normal functions need the inline keyword.

inline int sum(int i, int i2) { //Inline function
return i1+i2;
}

class MyClass {
public:
int getI();
int setI(int i2) { i = i2; } //Inline by default
int i;
};

inline int MyClass::getI() { //Inline by keyword
return i;
}

- Note that calling a function inline is a request, not a guarantee. Functions that are expanded inline may actually be slower if they are large or if there are certain other conditions. It is up to the compiler to determine whether to expand a function inline or not. It is not a good idea to call all your functions inline; it should only be used on short, simple functions called many times.


That is a basic introduction to classes. Reply if you have questions, comments, etc.

Edited by qwijibow, 28 February 2007 - 01:40 PM.
Fixed a few syntax errors


#2 quinciest

quinciest

    Member [ Level 1 ]

  • Members
  • 41 posts

Posted 01 February 2007 - 04:57 AM

thanks for the tutorial
although i've read it in book
but i more understand read this one

#3 qwijibow

qwijibow

    Way Out Of Control - You need a life :)

  • Members
  • 1,366 posts
  • Location:Nottingham England
  • Interests:Computer / nerd related things (who would have guessed)<br />also. the following cartoons...<br /><br />South Park<br />King of the hill<br />Family guy<br />Sponge Bob Square pants<br />Simpsons

Posted 28 February 2007 - 01:36 PM

And Dont forget to end the class with a semi colon ';'

class
{
};

;)

#4 Guest_FeedBacker_*

Guest_FeedBacker_*
  • Guests

Posted 30 January 2008 - 01:15 PM

Thanks...
Very simple illustrations...!

-venkatraman.S

#5 Guest_FeedBacker_*

Guest_FeedBacker_*
  • Guests

Posted 09 May 2008 - 07:58 AM

Access private member function without using friend class
C++: Basic Classes

I want to use private member function in other class , how can I access without using friend.

-question by Aijaz Ahmad

#6 Gr33nN1nj4

Gr33nN1nj4

    Newbie [ Level 2 ]

  • [HOSTED]
  • 20 posts

Posted 11 August 2008 - 06:02 AM

Access private member function without using friend class

C++: Basic Classes
I want to use private member function in other class , how can I access without using friend.

-question by Aijaz Ahmad


You can't as that is the idea behind private functions/variables, think of them as globals but only for that class. What you could do(assuming you have access to the source) is create a public "proxy" function think simply passes the given variables to the private function. For private variables I would recommend implanting get/set functions.

example of a get/set
class MyClass
{
	public:
		MyClass() // :) never forget to initialize your values.. bad things will happen if you don't
		{
			number = 0;
		}

		virtual int get_number() // Returns the value of the private member number
		{
			return number;
		} 

		virtual void set_number(int value) // Sets number to equal value
		{
			number = value;
		}

	private:
		int number;
};

Edited by Gr33nN1nj4, 11 August 2008 - 06:05 AM.


#7 Guest_(G)Thang Doan Minh_*

Guest_(G)Thang Doan Minh_*
  • Guests

Posted 17 May 2009 - 05:40 PM

Thanks u very much ^^. Your notes are very useful for me. I wish all Learn programming books had clear ideals like yours. You make me to love C++ so more!

-reply by Thang Doan Minh

#8 Guest_(G)richard_*

Guest_(G)richard_*
  • Guests

Posted 11 December 2009 - 12:28 PM

struct/class difference correctionC++: Basic ClassesA struct is not the "exact same" as a public classFrom C++ standard (11.2.2):"In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class."Additionally, (11.2):"Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default."-reply by richard

#9 vistz

vistz

    Member [ Level 2 ]

  • Members
  • 66 posts
  • Gender:Male
  • myCENTs:58.24

Posted 28 September 2010 - 03:50 PM

Although I haven't done extensive programming in C++, I have found that many of the practices in Java are also implemented in C++. Of course, there's the addition of pointers that I have to worry about also.

#10 yordan

yordan

    Way Out Of Control - You need a life :)

  • [MODERATOR]
  • 4,745 posts

Posted 29 September 2010 - 08:58 AM

Of course, there's the addition of pointers that I have to worry about also.

By the way, the pointer thing is one of the most inportant functionalities in C and C++.

#11 vistz

vistz

    Member [ Level 2 ]

  • Members
  • 66 posts
  • Gender:Male
  • myCENTs:58.24

Posted 25 October 2010 - 11:16 PM

By the way, the pointer thing is one of the most inportant functionalities in C and C++.

And I also know that allocating memory is also an important factor



Reply to this topic



  


0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users