수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1692079
  • Today | 223
  • Yesterday | 564

2 Articles, Search for 'Classes'

  1. 2007/07/27 C++ in theory: Bridging Your Classes with PIMPLs
  2. 2007/07/27 Introduction to Objects and Classes in C#
Programming/C++2007/07/27 17:10

C++ in theory: Bridging Your Classes with PIMPLs

출처 : http://www.devarticles.com/c/a/cplusplu ··· impls%2F

C++ in theory: Bridging Your Classes with PIMPLs
(Page 1 of 4 )

Very often, when a program takes longer to compile after you have made what appear to be trivial changes, the blame can be laid at the door of dependency chains between header files. One change can trigger the need for a massive rebuild. J. Nakamura explains a way to make header files insensitive to any change -- thus saving all that rebuild time -- by using pimpl.


Looking For Problems

Large development projects can become a drain... not just on your brain, but on your valuable time as well. When you notice increasing compilation time after making what you thought to be trivial changes, you can claim to have found a problem (some might say that you are looking for one). The application might run fine and be without bugs, but those increasing build times do not really speed up the development process. They are also very annoying when you are making small changes in a debug cycle.

Most often the cause for these extreme build times can be found in large dependency chains between your header files. Consider the following header files:

// MyBase.h
class MyBase {
public:
  int foo();
};

// MyDerived.h
#include “MyBase.h”
class MyDerived : public MyBase {
public:
  int bar();
};

If you make a change to MyBase.h (let's assume you need a new private or protected member variable), MyDerived and everything, including its header file, will have to be recompiled as well. You can imagine that in a large project, many header files will be dependent on each other, often many levels deep. At a certain point you will notice that you are becoming reluctant to make changes to a class, simply because these changes will trigger a massive rebuild (and might evoke some unpleasant primitive reactions in your colleagues).

There are tools available to analyze these dependencies. Personally I prefer to use Doxygen, which is used to generate documentation from sources. Doxygen can use ‘dot’ from GraphViz to generate nice pictures of header file dependencies. Best of all, it is free!

C++ in theory Bridging Your Clsasses with PIMPLs

There are ways to minimize the dependency problem -- for example, by forbidding coders to include header files in header files! But even so, your changes to MyBase.h will trigger a rebuild of MyDerived.cpp, since that is the file that includes the MyBase header now.

Wouldn't it be nice to be able to make the header file insensitive to any change? We would like to prevent recompilation when making changes to a private interface. This is where we use pimpl for [Sutter].

C++ in theory: Bridging Your Classes with PIMPLs - The Private Implementation
(Page 2 of 4 )

The private implementation is a variation of the Bridge Pattern [Gamma], which is intended to decouple an abstraction from its implementation, so that the two can vary independently.

When you take a look at the C++ header and class declaration, you will notice that both the public and private interface is usually declared at the same location. Conceptually this is quite strange: in effect, the class lets you peek at its private parts, which should be of no concern to you. So let's hide it!

// MyClass.h
class MyClassImpl;    // forward declaration
class MyClass {
public:
  MyClass();
~MyClass();
  int foo();
private:
  MyClassImpl *m_pImpl;
};

The only visible private member variable in our class is the pimpl. We defined a forward declaration of the private implementation class; we don’t need any further information about it. The compiler needs to know how much memory to reserve for MyClass. Since we are only storing a pointer (which on my win32 platform is 4 bytes big), the compiler doesn’t care what the memory layout of MyClassImpl looks like.

Unless you make changes to the public interface, this header file is unlikely to change! Lets take a look at the implementation.

// MyClass.cpp
class MyClassImpl {
public:
int foo() {
var*=var;
return bar();
}
int bar() { return var & 0xFF; }
int var;
};

MyClass::MyClass()
  : m_pImpl(new MyClassImpl)
{}

MyClass::~MyClass()
{
try { delete m_pImpl; }
catch (...) {}
}

int MyClass::foo()
{ return m_pImpl->foo(); }

The implementation class is defined in our source file, literally confined to the source implementation of our class. Any changes to our implementation class (the introduction of new member variables and member functions, for example) will trigger no recompilations outside this source file.

Basically all public functions redirect the call to the function in the private implementation when you implement a pimpl, although this is not strictly necessary. MyClass::foo() could also be implemented as:

int MyClass::foo() {
  m_pImpl->var*=m_pImpl->var;
  return m_pImpl->bar();
}

I consider it to be more effective and cleaner to just redirect the call to the pimpl. It also saves you multiple pointer dereferences.

The destruction of the pimpl is wrapped in a try-catch block, because we don’t want any exceptions to escape our own destructor. We do this because, when MyClass is destroyed by the exception-handling mechanism during the stack-unwinding part of exception propagation, any exceptions triggered during this destruction will force C++ to call the terminate function [Meyers]. Immediate termination of your application is one of the worst things that can happen to it!

C++ in theory: Bridging Your Classes with PIMPLs - Pimpl Drawbacks
(Page 3 of 4 )

You do pay a price for pimpls when it comes to performance. Let's set up some code:

#include <stdio.h>
#include <time.h>

class MyClassA {
public:
  MyClassA( ) : c(0) {}
  char foo( ) { return c; }
  char c;
};

class MyClassB {
public:
  MyClassB( ) : m_pImpl(new MyClassA) { }
  ~MyClass( ) { try { delete m_pImpl; } catch ( ... ) { } }
  char foo( ) { return m_pImpl->foo( ); }
private:
  char c;
  MyClassA *m_pImpl;
};


Here we have set up MyClassA to be the private implementation of MyClassB. We are going to measure how much performance overhead the function indirection and memory allocation require.

int main(int argc, char *argv[])
{
clock_t start, finish; // stores time values
for (int count = 0; count < 10; ++count)
{
  /* our test code will go here */
}
return 0;
}

Each construction/deconstruction needs to allocate/free memory.

Since the implementation is hidden in a separate class behind a pointer, every time our pimpled class is created, we need to allocate memory on the heap. And every time our pimpled class is destroyed, we need to free memory. Compared to common operations like function calls, memory allocation and deallocation are relative expensive operations.

Normally you would not notice or worry about this performance cost, but when you have to construct/destruct an array of your pimpled object repeatedly, you will notice a difference:

  start = clock();
  for (int i = 0; i < 10; ++i )  MyClassA arryA[0xffff];
  finish = clock();
  int durationA = finish – start;
  (void)printf(“ticks spent on MyClassA: %d\n”, durationA);

  start = clock();
  for (int j = 0; j < 10; ++j )  MyClassB arryB[0xffff];
  finish = clock();
  int durationB = finish – start;
  (void)printf(“ticks spent on MyClassB: %d\n”, durationB);

clock() calculates the processor time used by the calling process; we can use this to measure how much time is spent on constructing and destructing MyClassA arryA[0xffff] and MyClassB arryB[0xffff] 10 times. I prefer to cast the result of printf to void (it returns the number of characters printed or a negative value if an error occurs), just to make it clear that we are ignoring the return value.

When you run the sample, you will notice that the construction of the pimpled class takes a lot more time than the non-pimpled one. On my PIV 3Ghz the result was:

ticks spent on MyClassA: 31
ticks spent on MyClassB: 719

Though the sample might be a bit extreme, you can see that the difference is not trivial. Remember that the construction of an n-array of objects, constructs n objects on the stack for you. In this case it means that the MyClassB constructor is called n times, performing n allocations on the heap!

To make things worse, this example doesn’t do anything with the array, and since it immediately goes out of scope, the destructor is called n times as well.

Access to hidden members comes at the cost of at least one extra indirection.

Each access of a member in the pimpled class can require at least one extra indirection. A pointer dereference can be quite an extra cost if the code is called often:

  MyClassA aObj;
  start = clock();
  for (int k = 0; k < 0xffffff; ++k)  (void)aObj.foo();
  finish = clock();
  durationA = finish – start;
  (void)printf(“ticks spent calling MyClassA::foo(): %d\n”, durationA);

  MyClassB bObj;
  start = clock();
  for (int l = 0; l < 0xffffff; ++l)  (void) bObj.foo();
  finish = clock();
  durationB = finish – start;
  (void)printf(“ticks spent calling MyClassB::foo(): %d\n”, durationB);

Running another extreme sample, my result was:

ticks spent calling MyClassA::foo(): 1500
ticks spent calling MyClassB::foo(): 3156

Again, this is not a trivial difference when the code is executed often!

Access to public members comes at the cost of an extra indirection.

Sometimes the private implementation needs to access public member functions of the pimpled class. Storing a “back pointer” to the visible object can easily do this. By convention, this back pointer is usually named “self.”

// MyClass.h
class MyClass {
public:
  MyClass();
  ~MyClass();
  void foo();
void bar();
private:
  MyClassA *m_pImpl;
};

// MyClass.cpp
class MyClassImpl {
public:
  MyClassImpl(MyClass *_self) : self(_self) {}
  void foo() { self->bar(); }
};
MyClass::MyClass()
  : m_pImpl(new MyClassImpl(this))
{}
MyClass::~MyClass()
{
try { delete m_pImpl; }
catch (...) {}
}

Looking at the previous example, it is clear that an extra indirection back will drive the performance cost even further up.

There is a small space overhead.

“Space overhead?” you might ask -- and you might not think this is a big deal. When you have a lot of small objects which you have pimpled, however, that extra pointer does start to count (when you need a back pointer, you will actually need two extra pointers). Try the following on the test code above:

  (void)printf(“sizeof MyClassA: %d\n”, sizeof(MyClassA));
  (void)printf(“sizeof MyClassB: %d\n”, sizeof(MyClassB));

Result will vary among compilers but the overhead I have is actually 7 bytes:

sizeof MyClassA: 1
sizeof MyClassB: 8

Even though a pointer only costs 4 bytes on my machine, the compiler aligns it on a 4-byte boundary, wasting 3 bytes (char c takes one byte). The overhead will be even larger on an AS/400 or 64-bit machine. Of course you can configure this in your build settings...but that is not my point.

C++ in theory: Bridging Your Classes with PIMPLs - Summary
(Page 4 of 4 )

The pimpl allows you to decouple the interface of your class from its implementation. On top of that, the implementation is not permanently bound to the interface. Any compile time dependencies are completely eliminated with the pimpl. This frees you from the fear to make changes to the implementation.

So use the pimpl when you want to hide the implementation details of your class. Before you do, however, make certain that you understand the performance penalties involved.

References

[Sutter] Exceptional C++ item 26~30.

[Gamma et all] Design Patterns – Bridge.

[Meyers] More Effective C++ item 11


"C++" 카테고리의 다른 글
  • DLL Conventions: Issues and Solutions (0)2007/07/27
  • More on Handling Basic Data Types (0)2007/07/27
  • C++ in theory: Bridging Your Classes with PIMPLs (0)2007/07/27
  • C++ In Theory: The Singleton Pattern (0)2007/07/27
  • <iostream> vs. <iostream.h> (0)2007/07/03
2007/07/27 17:10 2007/07/27 17:10
Posted by webdizen
Tags Bridging, C++Keyword C++, Classes, PIMPLs
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/3102

Leave your greetings.

[로그인][오픈아이디란?]

Programming/C#2007/07/27 09:27

Introduction to Objects and Classes in C#

출처 : http://www.devarticles.com/c/a/c-sharp/ ··· sharp%2F

Introduction to Objects and Classes in C#
(Page 1 of 9 )

In this article Michael introduces us to C#, as well as attempts to demystify the theory behind "Object and Classes" in OO Programming.

In this article I will explain some of the concepts behind object-oriented programming in C#, including objects and classes. To read this article you should have some basic understanding of the C-Sharp language.

Read the whole article because there are some concepts you may not fully understand until you finish the article. And we will revisit all the concepts more than once when I see it's appropriate in future articles; so don't worry at all.

Introduction to Objects and Classes in C# - Introduction
(Page 2 of 9 )

OOP stands for Object-Oriented Programming. OOP is relatively a new way to program computer applications. In the past, OOP programmers used to create computer applications using procedural-programming (or structured-programming). But, when OOP solved a lot of the problems of the procedural-programming, most programmers and developers began using OOP languages. In procedural- programming all the program functionality is written in a few modules of code or maybe one module (depending on the program). These modules depend on one another and sometimes changing a line of code requires you to rewrite the whole module again and maybe the whole program. 

In Object-Oriented Programming programmers write independent parts of a program called classes. Each class represents a part of the program functionality and these classes can be assembled to form a program. When you need to change some of the program functionality all you have to do is to replace the target class which may contain the problem that needs change. So, OOP applications are created by the use of classes and these applications can contain any number of classes. This will get us to discuss the Class and Object concept.


Classes and objects

You may find it a little difficult to understand the class and object story; but, I will try to do my best in explaining it. Actually the class and object concept is related to each other. Some beginners don't care about understanding it clearly so I think they will have a hard time learning C#.

Object-Oriented concepts take most of their functionality from the real-life concepts. For example, I will discuss the concept of Classes and Objects of the world first and then you will understand the computer's Classes and Objects before I even write anything about it.

Introduction to Objects and Classes in C# - World's Classes and Objects
(Page 3 of 9 )

In our world we have classes and objects for those classes. Everything in our world is considered to be an object. For example, people are objects, animals are objects too, minerals are objects; everything in the world is an object. Easy, right? But what about classes?

In our world we have to differentiate between objects that we are living with. So we must understand that there are classifications (this is how they get the name and the concepts of the Class) for all of those objects. For example, I'm an object, David is object too, Maria is another object. So we are from a people class (or type). I have a dog called Ricky so it's an object. My friend's dog, Doby, is also an object so they are from a Dogs class (or type).

A third example: I have a Pentium 3; this is an object.  My friend has a Pentium 4, so this is another object and they are from a Computers class (or type). Now I think you understand the concept of the Class and Object, but let me crystallize it for you. In our world we have classifications for objects and every object must be from some classification. So, a Class is a way for describing some properties and functionalities or behaviors of a group of objects. In other words, the class is considered to be a template for some objects. So maybe I will create a class called person which is a template of the functionality and the properties of persons.

Introduction to Objects and Classes in C# - Programmer’s Classes and Objects
(Page 4 of 9 )

A C# Class is considered to be the primary building block of the language. What I mean by the primary building block is that every time you work with C# you will create classes to form a program. We use classes as a template to put the properties and functionalities or behaviors in one building block for a group of objects and after that we use the template to create the objects we need.

For example, we need to have persons objects in our program so the first thing to do here is to create a class called Person that contains all the functionalities or behaviors and properties of any person and after that we will use that class (or template) to create as many objects as we need. Creating an object of a specific class type is called "an instance of the class". Don't worry if you didn't grasp it 100% and don't worry if you don't know what the class and object's properties and functionalities or behaviors are because we are still in the beginning.  Until now I haven’t provided any code examples. So let's take a brief of what is a class and what is an object:

The class: A building block that contains the properties and functionalities that describe some group of objects. We can create a class Person that contains:

  1. The properties of any normal person on the earth like: hair color, age, height, weight, eye color.
  2. The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Later we will see how we can implement the functionalities or behaviors and properties.

There are 2 kinds of classes: The built-it classes that come with the .NET Framework, called Framework Class Library, and the programmer defined-classes which we create ourselves.

The class contains data (in the form of variables and properties) and behaviors (in the form of methods to process these data). We will understand this concept later on in the article.

When we declare a variable in a class we call it member variables or instance variables. The name instance come from the fact that when we create an object we instantiate a class to create that object.  So instance of a class means an object of that class and instance variable means variable that exists in that class.

The object: It's an object of some classification (or class, or type) and when you create the object you can specify the properties of that object. What I mean here is: I, as an object, can have different properties (hair color, age, height, weight) than you as another object. For example, I have brown eyes and you have green eyes.  When I create 2 objects I will specify a brown color for my object's eye color property and I will specify a green color for your object's eye color property.

So to complete my introduction to classes we must discuss properties and variables.

Introduction to Objects and Classes in C# - Properties and Variables
(Page 5 of 9 )

Variables declared in a class store the data for each instance.  What does this mean? It means that when you instantiate this class (that is, when you create an object of this class) the object will allocate memory locations to store the data of its variables. Let's take an example to understand it well.

class Person
{
   public int Age;
   public string HairColor;
}

This is our simple class which contains 2 variables. Don't worry about public keyword now because we will talk about it later. Now we will instantiate this class (that is, when you create an object of this class).

static void Main(string[] args)
{
   Person Michael = new Person();
   Person Mary = new Person();

   // Specify some values for the instance variables
   Michael.Age = 20;
   Michael.HairColor = "Brown";
   Mary.Age = 25;
   Mary.HairColor = "Black";
   // print the console's screen some of the variable's values
   Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age,
       Mary.Age);
   Console.ReadLine();
}

So we begin our Main method by creating 2 objects of type Person. After creating the 2 objects we initialize the instance variables for object Michael and then for object Mary. Finally we print some values to the console.  Here, when you create the Michael object, the C# compiler allocates a memory location for the 2 instance variables to put the values there. Also, the same thing with the Mary object; the compiler will create 2 variables in memory for Mary object. So each object now contains different data. Note that we directly accessed the variables and we put any values we wanted, right?  But wait there is a solution to this problem. We will use properties.

Introduction to Objects and Classes in C# - Properties
(Page 6 of 9 )

Properties are a way to access the variables of the class in a secure manner. Let's see the same example using properties.

class Person
{
   private int age;
   private string hairColor;
   public int Age
   {
       get
       {
       return age;
       }
       set
       {
           if(value <= 65 && value >= 18)
           {
               age = value;
           }
           else
               age = 18;
       }
   }
   public string HairColor
   {
       get
       {
           return hairColor;
       }
       set
       {
           hairColor = value;
       }
   }
}

I made some modifications, but focus on the new 2 properties that I created. So the property consists of 2 accessors. The get accessor, responsible of retrieving the variable value, and the set accessor, responsible of modifying the variable's value. So the get accessor code is very simple. We just use the keyword return with the variable name to return its value. So the following code:

get
  {
   return hairColor;
  }

returns the value stored in hairColor.

[Note]

The keyword value is a reserved keyword by C# (that is, reserved keywords means that these keywords are owned only by C# and you can't create it for any other purposes. For example, you can't create a variable called value .If you did, the C# compiler would generate an error. To make things easier, Visual Studio.NET will color the reserved keywords in blue.)

[/Note]

Let's put this code to work and then discuss the set accessor..

Introduction to Objects and Classes in C# - Reworked
(Page 7 of 9 )

static void Main(string[] args)
{
   Person Michael = new Person();
   Person Mary = new Person();

   // Specify some values for the instance variables
   Michael.Age = 20;
   Michael.HairColor = "Brown";
   Mary.Age = 25;
   Mary.HairColor = "Black";

   // print the console's screen some of the variable's values
   Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age,
       Mary.Age);
   Console.ReadLine();
}

Here I created the same objects from the last example, except that I used only properties to access the variable instead of accessing it directly. Look at the following line of code

Michael.Age = 20;

When you assign a value to the property like that C# will use the set accessor. The great thing with the set accessor is that we can control the assigned value and test it; and maybe change to in some cases. When you assign a value to a property C# changes the value in a variable and you can access the variable's value using the reserved keyword value exactly as I did in the example. Let's see it again here.

set
  {
      if(value <= 65 && value >= 18)
      {
          age = value;
      }
      else
          age = 18;
  }

Here in the code I used if statement to test the assigned value because for some reason I want any object of type Person to be aged between 18 and 65. Here I test the value and if it is in the range then I will simply store it in the variable age. If it's not in the range I will put 18 as a value to age.

Introduction to Objects and Classes in C# - Creating Objects and Classes
(Page 8 of 9 )

We create a class by defining it using the keyword class followed by the class name:

class Person

Then we open a left brace "{" and write our methods and properties.  We then close it with a right brace "}". That's how we create a class. Let's see how we create an instance of that class.

In the same way as we declare a variable of type int we create an object variable of Person type with some modifications:

int age;
Person Michael = new Person();

In the first line of code we specified integer variable called age. In the second line we first specified the type of Object we need to create, followed by the object's name, followed by a reserved operator called new.  We end by typing the class name again followed by parentheses "()".

Let's understand it step-by-step. Specifying the class name at the beginning tells the C# Compiler to allocate a memory location for that type (the C# compiler knows all the variables and properties and methods of the class so it will allocate the right amount of memory). Then we followed the class name by our object variable name that we want it to go by. The rest of the code "= new Person();" calls the object's constructor. We will talk about constructors later but for now understand that the constructor is a way to initialize your object's variable while you are. For example, the Michael object we created in the last section can be written as following :

Person Michael = new Person(20, "Brown");

Here I specified the variable's values in the parameter list so I initialized the variables while creating the object. But for this code to work we will need to specify the constructor in the Person class -- I will not do that yet as constructors will come in a later article.

Introduction to Objects and Classes in C# - Conclusion
(Page 9 of 9 )

In this article, I gave you a concise introduction to classes and objects. I will complete the discussion in my next article, as well as discuss constructors and building block scope. I hope you’ve learned something new thing from this first article.

Introduction to Objects and Classes in C#, Part 2
(Page 1 of 4 )

After I wrote the article named Introduction to Objects and Classes in C#, I got a lot of e-mail messages asking me to create a series of articles about Objects and Classes. Actually this was a few months back (sorry for being late), but I'm here again with part two. In Part one, I explained the concepts behinds Objects and Classes but I didn't discuss why Object Oriented Programming (OOP) uses the Object and Class technique. Today, I will discuss the advantage of Objects and Classes with more details on how to understand your problems and develop your Objects for your solution.

Because this series targets the true beginners, I will not use any technical expressions and I will prefer to explain concepts by examples. I presume that readers have a basic knowledge of C# (control the flow of the program, using methods and arrays, namespaces & assemblies).

The first thing that you should know about C# programming is that it uses the Class to include the data (in part one, I said that data can be stored in instance variables in the class) and methods to process that data. Think about it in the next example:

class Test
{
   
public int Add(int x, int y)
   
{
       
return x + y;
   
}
}

The class Test contains a method called Add (which add to integers and return the result) is a good example for what we are talking about. I said that the Class includes data and there are methods to process that data, here the class test includes the method Add() which takes two integer numbers to add them and this is the functionality of the method. The application that will use the Test class can be something like the following:


public

class Class1
{
   
public Class1()
   
{
       Test t1
= new Test();
       Console
.WriteLine(t1.Add(5,4));
   
}
}

The concept of Objects & Classes helps you hide your code implementation from the user of your class. In other words, if you develop a class for your friend to use, he doesn't have to know how you created the methods of that class in order to use it; he'll just need to know how to use it, and what functionality is offered by your class members. The point here is that you don't have to know how another developer developed a certain class; you just have to know how to interface with it. And I said in the first part, when you develop programs with C# you will develop classes. Note that this is not like C programming, where the programming primary building block was the function (or methods, in C#). Finally, remember that C# defines other types like structures, enumerations. We'll learn about these in future articles.

In C programming language, programmers develop functions to form their applications. These functions contain the code of the program. The problem is that in large programs, if you have to modify just one line of code you may have to modify many functions to fit in the new modifications. (In procedural languages, functions depend on each other.) But in C#, we write classes as our primary building blocks, and because classes hide their code implementation -- and only the methods of these classes are accessible to the applications that use them -- if we must change something inside the class, we will do it without changing the code of the applications that uses our classes.

Introduction to Objects and Classes in C#, Part 2 - Comments
(Page 2 of 4 )

When you write applications in C# try to use comments to describe exactly how your application performs and why; try to make your application easy to understand and easy to maintain. Think about it this way: if you were to come back to your application five years after you wrote it, would you know what every line of code meant and did? What if someone was developing an application and they were trying to read through your code? Without documentation, this is difficult even for the most experienced programmers.  

I think that you want to know more about classes so let's write a class and then discuss  new concepts.

The Person Class

Here's a simple class called Person


class Person

{

   
// These are 3 private instance variables
   // for now just consider them instance members of
   // that class
   private string firstName;
   private string lastName;
   private int age;

   // This called the default constructor
   public Person()
   {

       
firstName = "Unknown";
       lastName
= "Unknown";
       age
= 0;

   }
   
   
// This also a Constructor and we will understand
   // the use of it and why we create constructors
   public Person(string fName, string lName, int pAge)
   {
       firstName = fName;
       lastName = lName;
       age = pAge;
   }

// This is a method just writes a string to the console.
// this string consists of the 3 variables and
// displaying the information about the person.
public void PersonInfo()
{

Console.WriteLine("First Name = {0}, Last Name = {1} and his age = {2}",
firstName
, lastName, age);

}

}

Let's break this down:

You're probably curious about private string firstName, private string lastName, and private int age. These are called instance variables, and as you know from the first part of that article, when you create objects from a given class (for example, the person class) you create an instance of that class. That's why we call the variables declared the body of the class (but not inside any method of that class) an instance variable. When you create an objects of that class C# compiler will allocate separate memory locations for the instance variables of each object. Thus, the object named Michael (of type Person) will contain its own values for these instance members, as will the object Prakhar (of type Person). You can say that the consumer application (the application that will use your class) will provide the values of these instance variables for each object created of that type.

NOTE About the keywords private and public in the class, they called access modifier keywords. When developing C# class you will use the access modifier keywords to specify the scope of the member. Each instance variable, method, or any other type you create inside a class called a member. C# gives you the power to specify the scope of the member using these access modifiers.

Introduction to Objects and Classes in C#, Part 2 - What's a Scope?
(Page 3 of 4 )

Simply, the scope of a type (a variable, a method, or a class) is where you can use that type in your program. In other words, the scope defines the area of the program where that type can be accessible and referenced.

When you declare a variable inside a block of code (like a method or an if statement structure), it will have a local scope, and it will be called a local-variable. Local scope means that you can't refer to that variable outside that block of code. Consider the next example.


class Test

{
   
public void Test1()
   
{
       int x 
= 0;
           
// some code goes here that uses the x variable
   }
   
   
public void Test2()
   
{
       Console
.WriteLine(x);
   
}
}


Try to instantiate this class and you will get a compile-time error inside method Test2() telling you that the name x doesn't exist and that's because x is a local variable to the method Test1() and method Test2() doesn't know anything about it. So x has a local score to method Test1() only. Consider the next example.


class Test

{

   public
void Test1()
   
{
       int x 
= 0;

       if(
x == 0)
       
{

           
Console.WriteLine("x equal to 0");
       
}
   
}
}

Here, the method Test1() declares a local variable x (now x has a local-scope to the method). Try to instance this class and compile the code. It will work! Some beginners think that because I said that x has a local scope to method Test1() it will not be referenced from nested block (like the one we have here, the If statement) but that's not true because any nested block inside Test1() method can refer x because x is local for the method and its all blocks of code.

NOTE  There are 2 kinds of scopes: block scope (the one that we just finished), and a class scope (which we will talk about later in this article). Now, about the keywords private and public in the class person, you can use these access modifier keywords to define the scope of your variables, methods, or even your classes. There are other access modifiers but I will talk about them in a later article when I will explain the concepts of inheritance.

Instance variables declared using the access modifier keyword private will be accessible to the methods between the opening left brace "{" and the closing right brace "}" (which define the body of the class) only. In other words, when you declare an instance variable like in the following example:


public

class Class2
{
   
private int x;
}

public class
Class3
{
   void testing
()
   
{
       x
== 100;
   
}
}

In this example, you will get a compile-time error telling you that you that the name X doesn't exist inside the Class3. Using the keyword private, you explicitly tell the compiler "Don't show this member to any other class." (So you are hiding it inside the class.)

Introduction to Objects and Classes in C#, Part 2 - Private Members Only?
(Page 4 of 4 )

What about objects of that class? Can they access the members declared as private?

In short, no, the objects of this class will not see the private member, but it will have it's own copy because as we said before the class is just a template for the contents of its object. I prefer to discuss it using an example:


public

class Class2
{
   
private int x = 100;
}

And then I will instance 2 objects of that class inside the Main method


static void Main

(string[] args)
{
   Class2 c2
= new Class2();
   Class2 c3
= new Class2();
   
// Now Let's check if we can see
   // x inside any of these objects
   c2.
}

c2 and c3 are objects of type Class2() but look what happened when I typed the "." operator (which will get us all the accessible members of that class).

C#

There is no x here because it's private to the class. You may wonder why this feature exists. Sometimes you need to hide some values inside the class (ie. you don't want other classes or objects of that class to see these values), maybe because it's complex information, or it's private to your work, or the developers that will use your class (after it's compiled) will simply not benefit if they saw these variables or methods.

You can use the access modifier keyword public while you declare your variables to specify that you want your variable to be accessed by the other classes or any objects of this class. let's revise the the x variable in Class2 and check if we can see it or not (from objects of this class or other classes).


public

class Class2
{
   
public int x = 100;
}

Now let's see the result:

C#

Oh, yes we can see the x variable now because we made it public. And I will talk about Class Scope in a later article. For now, just play around with scopes. I think you'll have a lot of fun with these.

"C#" 카테고리의 다른 글
  • Introduction to Objects and Classes in C# (0)2007/07/27
  • Creational Patterns in C# (0)2007/07/27
  • Exception Handling in C# (0)2007/07/27
  • C# 키워드 목록 (0)2007/07/02
  • Event Handling in .NET Using C# (0)2007/06/26
2007/07/27 09:27 2007/07/27 09:27
Posted by webdizen
Tags C#, Classes, Objects
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/3100

Leave your greetings.

[로그인][오픈아이디란?]

«Prev  1  Next»

RSS HanRSS
Blog Image
webdizen
이곳은 컴퓨터에 대해 연구하고, 공유하고, 소통하기 위한 연구실입니다. 개인적으로는 OLAP, Data Mining, Semantic Web, Data Modeling에 대해서 연구하고 있습니다.

Categories

전체 (3009)
Webdizen (141)
Life (6)
Diary (16)
Blog (9)
IDEA (2)
Travel (10)
Book (16)
Photo (7)
Movie (8)
Music (14)
Leisure Sports (10)
Funny (6)
Hardware (121)
Software (120)
Windows (5)
Unix & Linux (120)
Installation (5)
Kernel (10)
System (34)
Develop (22)
X-Window (0)
Applicaton (31)
Security (4)
Framework (2)
Hadoop (2)
Programming (804)
Algorithm & Data Structure (1)
Assembly (38)
UNIX/Linux C (95)
C++ (128)
STL (4)
Java (38)
Win32 API (92)
ATL/COM (44)
MFC (151)
.NET (26)
WCF/WPF (4)
C# (28)
Network Programming (17)
Database Programming (12)
OpenGL / DirectX (13)
Multimedia Programming (0)
Game Programming (21)
Parallel Distributed Progra... (0)
Reverse Engineering (0)
Debugging (9)
Python (1)
Ruby (1)
Ruby on Rails (1)
QT (4)
GTK (0)
JSP (0)
PHP (6)
ASP.NET (6)
ASP (2)
Development (28)
Useful Library (2)
Data Modeling (0)
Database (105)
Oracle (4)
MSSQL (41)
MySQL (2)
Data Warehouse (2)
Data Mining (4)
Network (66)
Web (79)
DHTML (4)
XHTML (1)
Javascript (1)
CSS (1)
AJAX (9)
XML (11)
Flex (1)
Silverlight (3)
Security (91)
DoS (1)
Kernel (10)
Scanning (3)
Sniffing (0)
Spoofing (4)
Overflow (28)
Web (11)
Shell (10)
Format String (14)
Window (2)
Embedded (70)
Multimedia (27)
Mobile (14)
Graphic (24)
Management (633)
Knowledge (581)
Hadoop (0)

Notice

  • 메타 블로그 사이트에 등록
  • 새해 맞이 블로그의 변화
  • 블로그 명칭 변경
  • 도메인(www.webdizen.net) 구...
  • TEXTCUBE 1.6.1로 업그레이드...

Tags

  • 패킷 캡처
  • Volatile
  • 키워드
  • 조니워커 블랙
  • 대한민국
  • Iterator
  • 백업
  • /dev/random
  • Template
  • SYN attack
  • 소프트웨어
  • Canon
  • proc
  • 고딕지구
  • 샌프란시스코
  • CFile
  • OLAP 큐브
  • G.ho.st
  • RC헬기
  • 까무스

Recent Articles

  • 트위터(Twitter)의 시작!.
  • 청년 리더의 조건.
  • 애플의 타블렛 PC - 아이패드....
  • 미래의 인터페이스 - 육감 기....
  • 기초발성법 동영상 강좌.

Recent Comments

  • 학교 과제물중 쓰레드에 대하....
    장진혁 03/17
  • 관리자만 볼 수 있는 댓글입....
    비밀방문자 03/12
  • 상대방의 이야기를 열심히 경....
    DoNuts 03/03
  • Lots of students know techn....
    Bobbi35Shannon 02/25
  • 좋은글 잘 보고 갑니다..
    Und_hacker 01/08

Recent Trackbacks

  • printf,scanf를 이용한 형식....
    yundream의 프로그래밍 이야기 03/10
  • 파일 열기/저장하기 CFileDialog.
    은마군의 나태블록 2009
  • World IT Show 2008.
    상우 :: Oranzie's BLOG 2008
  • cvs서버 설치하기.
    3인3색 2008
  • 속속 공개되는 Google Chart....
    PHP와 Web 2.0 2007

Archive

  • 2010/02 (1)
  • 2010/01 (6)
  • 2009/12 (5)
  • 2009/09 (3)
  • 2009/08 (1)

Calendar

«   2010/03   »
일 월 화 수 목 금 토
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      

Bookmarks

    • Administration
      • IIS.NET
      • NTFAQ
      • OS의 모든 것
      • 리눅스포털
    • Database
      • SQL Server Central
      • SQL Team
    • Development
      • .NET Heaven
      • ASP Alliance
      • ASP.NET 2.0
      • Bullog.net
      • C# Corner
      • C++ (C PlusPlus.com)
      • C++ Reference
      • CodeGuru
      • CodePlex
      • DebugLab
      • Dev Articles
      • Devpia
      • DotNet Junkies
      • DotNet Zone
      • Driver Online
      • GOSU.NET
      • HOONS 닷넷
      • Joinc 팀블로그
      • KOSR
      • MSDN Home Page
      • OSR Online
      • Sky.ph - 개발자 커뮤니...
      • TAEYO.NET
      • The Code Project
      • WindowsClient.net
      • 김상욱의 개발자 Side
      • 조인시 위키
    • Human Networks
      • belief21c's e-space
      • I think I can
      • Invisible Rover's Blog :D
      • Rodman®
      • ■ Feel So Good~! ■
      • 까만 나비
      • 나를 가꾸는 시간.
      • 나만의 즐거움~~!
      • 단녕
      • 상우 :: Oranzie's BLOG
    • Information Technology
      • Microsoft TechNet
      • 지디넷코리아 - 글로벌...
    • Security
      • FoundStone
      • milw0rm
      • NewOrder
      • OpenRCE
      • Phrack.org
      • Reverse Engineering b1...
      • Reverse Engineering Team
      • RootKit
      • SecurityFocus
      • SecurityXploded by Nag...
      • Wow Hacker
      • Zone-H
Textcube
Louice Studio Inc.
Powered by Textcube. Original designed by Tistory.