Thursday, May 31, 2007

Simple Question in OOPs and C++

These are some of the simple question in OOPs and C++ .
These are from my notes while preparing for exams and getting my job training.
I just wanted to keep it safe here and will be happy if these questions will be of any help to you.
I will update the blog if I get any more questions.

1. What is a class?
Ans: A class is a represents the method of binding data and the related functions together.
Class is a blueprint from which objects are created and manipulated.

2. What are the objectives of class declaration?
Ans: A class declaration is done to specify the properties and data required to model the entity in an application.

3. What are different data assessors used in C++?
Ans: Private, public, protected.

4. What is the default level access specified in a c++ program?
Ans: Private.

4. What is data hiding?
Ans: Defining the accessor properties for a method, variable using the keywords private/public is called data hiding.

5. What are member functions?
Ans: Members that are class specific are called member functions.

6. How to declare a member function?
Ans: Member functions are declared as a prototype in a class. The exact function is declared outside the class.

7. What is the syntax of a member function in C++?
Ans: Return type Class :: FunctionName(arguments)
{
Function body
};

8. What is “::” called and what does it signify?
Ans: “::” is called a “scope resolution operator” it signifies the belonging of a particular function or member to a particular class.

9. What are the ways in which arguments can be passed to a function in C++ , how does it differ from passing parameters in C# ?
Ans: In c++ parameters can be passed in three forms: Value, reference and pointer.
In C# parameters can be passed either as value or as a reference.

10. How is member function passed to a class as ------?
Ans: As a pointer.

11. What is a constructor?
Ans: Constructor is a member function that creates an instance of the class. A Constructor has the same name as the class for which the object is being created for.

12. What is memory pool?
Ans: Memory pool is the memory space provided to a program to use at run time.

13. What do you mean by Dynamic memory allocation?
Ans: Memory space is provided to a program during run time this is called dynamic memory allocation.

14. How the operator “new” works?
Ans: Operator “new “first allocates the required memory to object from the memory pool, and then calls the constructor of the class. The constructor the address of the memory allocated to the object.

15. What is a destructor?
Ans: Destructor is a member function called by the class to deinitialize the objects that are initialized by the constructor.

16. When shall a destructor be called and how should it be called?
Ans: A destructor is called whenever the object of the class goes out of scope. The syntax of destructor is class name preceded by a “~” sign.
Ex: Destructor for class1 is ~class1 ();

17. How do you de-allocate the memory space given to a member of a class?
Ans: Using the function Delete ().

18. What is the difference between Delete and De-initialize functions?
Ans: De-initialize function, de-initializes or destroys objects in a function. Whereas delete function releases the memory of the object initialized in a class.

19. What do you mean by composition and composite objects?
Ans: Composition refers to the “component relationship” between two objects ,where one object is dependent on the other.For instance, let us take the example of a class named “Student” in this class the “Student Name” and “Course taken “are dependent on each other. Such objects are called composite objects. Composition is initialized for mutally dependent objects.

20. What is the relationship between constructor, destructor and composition?
Ans: The sequencing of constructor and destructor is dependent on composition. If we take the previous example then the destructor for “Course taken” cannot be called before destructor for “Student Name”.

21. Give the syntax to declare a composition.
Ans: Following is the example to show the composition for the example given above.
Class Student
{
Private:
String Student Name;
Int CourseNumber;
String Address;
Public:
Student (const String&, const Int&);
};
Student::Student (Const String& n, const Int& c): name (n), course(c)
{
}
Here whenever name object is created, course object is created and initialized automatically.
Whenever the composite object Student is destroyed the objects are de-initialized and destroyed in the reverse order of their initialization and creation.

So, in our example first the Student object is destroyed and initialized, then the course taken object and finally the name object.

22. What is association?

23. What is the syntax used to define an association?

24. Describe how would you create an association using address pointer?

25. What is Inheritance?
Ans: When we want to declare a class Class 2 which has features similar to a class Class1 defined earlier , then instead of declaring Class 2 again , we can derive it from Class1 .This is called inheritance.
To give a complete definition:
Inheritance is the process by which one object/class acquires the properties of another object/class.

26. What are the advantages of inheritance?
Ans: Code reusability and maintainability, reduces development time.

27. Are the private members of the base class available to child class?
Ans: No. Only Public and protected variables are accessible.

28. What is the syntax to inherit a subclass from a base class?
Ans: Subclass: public baseclass
{
}
29. If Class C inherits Class B and ClassB inherits Class A.Then what informations are present in Class C?
Ans: Informations from Both class A and Class B.This is called multilevel inheritance.

30. What is member initialization list?
Ans: Member initialization list is the information containing an entry call to derived class’s immediate base class.

31. If you say that member initialization list contains only the call to immediate base class of a derived class, how can you justify your answer for Q29?
Ans: The member initialization list contains only the call to immediate base class of the derived class but the immediate parent’s constructor invokes the immediate base class until the uppermost class is reached.

32. What is dynamic binding/late binding are the same or different?
Ans: Dynamic binding is same as late binding. This is the process of invoking appropriate behavior of an operation based upon the arguments.

33. Can you explain this concept?
Ans: Lets as take the example of “+” operator, the “+” operator can be used for addition of two integers or concatenation of two strings. The behavior of this operator in the program is known only during the run time not during compile time. If the variables are int “+” does addition. Otherwise “+” is used for concatenation. This is what is called late binding or dynamic binding.

34. What do you call this other than late binding /dynamic binding?
Ans: This process is also known as polymorphism. That is one operator taking multiple roles.

35. What is the most important property of polymorphism?
Ans: Polymorphism allows objects that have different internal structure to take the same function name.

36. What do you mean by overriding?
Ans: Overriding means changing the implementation of a function in a derived class.

37. How is polymorphism supported in C++?
Ans: By declaring the function virtual in base class and derived class.

38. What do you mean by Virtual function?
Virtual function is a function in derived class with features specific to the derived class.

39. So how a virtual function does differs from a general derived function?
Ans: A virtual function in a derived class has same function name, same parameters, same return type as that of the base class but the method implementation is different.

40. What are the two features available in c++ for error checking in development?
Ans: Const function and assert () macro.

41. What does the following declaration signify? int String(const *P)
Ans: It signifies that the value of the variable declared at address P should not be modified.
In case of modification the compiler throws an error.

42. How can u use assert () macro?
By including assert
The declaration is given as #include
The syntax to use assert macro is:
#include

Void class ClassName::FunctionName(arguments)
{
Assert (condition);
};
Here function name represents the function that represents error.
Assert macro checks for errors based on the condition.

43. Where is the assert macro generally placed in a function?
Ans: Assert macro is place at head as well as at the end of the function. It is placed at the head to evaluate the incoming parameter/arguments, and at the end to validate the object is in its proper state before the function terminates.

44. What is a fiend class in C++? What is its Syntax?
Ans: A class can access the private variables of other class by declaring the class as a friend class.
The syntax of friend class is friend class
Friend function

45. A friend class allows unrestricted access to the members of a class. True/False?
True.

46. What are the advantages and disadvantages of declaring a class as a fiend class?
Ans: Advantage: A declaring a class as a friend class allows the subclasses to access the private variables and functions.
Disadvantage: Declaring a class as a friend class allows other classes to modify the base class implementations of the functions. Which can cause complications in a program.

47. What do you mean by default initialization in C++?
When an object is passed as a value to a function, the compiler creates a local copy of the variable in the stack this is called default initialization.
Default initialization also happens when an object is returned back from a function by value.

48. What are the disadvantages of default initialization?
1. In default initialization, the initialized object of deleted buffer will not get the correct value.
2. The newly created object of the same type also points to the same dynamically allocated buffer.

49. What is shallow copy?


50. What do you mean by pure virtual function?
Ans: Declaring a function as pure virtual function ensures that the base class virtual function does not override the derived class function. That is whenever the function is called it is not the base class function but the derived class function.

51. Can a pure virtual function be called from a base class? Why?
Ans: No. Because the pointer to pure virtual function in pure virtual table is null. When the base class constructor calls a pure virtual function it gives a run time error.

52. What is the declaration for a pure virtual class function?
Ans: class BaseClass
{
Public:
Virtual void functionName() = 0;
};

53.What are the impoprtant concepts in OOP?
Ans: Abstraction,Inheritance, Polymorphism


mail me at: archita.dash@rediffmail.com

Wednesday, May 30, 2007

General .NET Interview Questions

These are some of the list of questions I have collected from various sites, while making my fundamentals and Concepts on C# and .NET strong.These question follow no particular order,these are listed as andwhen they were found. :)

1.what is the difference between panel and placeholder?

Ans:

2.What is querystring? What are various types of querystring? explain?


3. What is session? what are their types? Explain?


4. What are Serialization?


5.What is the need of delegates?


6. Explain what are value type parameters?


7. What is difference between compiler and runtime enivornment?


8. What is CLR?


9.What do you mean by static method and dynamic method?


10.What is difference between repeater control and datagrid?


11.What is difference between Response.Write() and Console.WriteLine() ?


12.What is main difference between ASP and ASP.NET?


13.What is IIS?


14.What are the various languages supported by .NET?


15.What is an assembly?


16.What is the base class of .NET?


17.What are various types of exception handling supported by .NET?


18.Describe some of the ADO.NET features.


19.

Tuesday, May 29, 2007

Understanding VC++.NET 2nd Installment

I was a little busy in a training so was unable to post this program early.
This is a simple Windows application program.Again I would like to say the inspiration and guidance is taken from msdn.Although I have changed the program a little, just to suite my own satisfactions.I give all credit to msdn.
So here it comes...

Creating a Windows Application:


1. Create a new VS 2005 project in VC++
2. In the Project Types pane, select CLR in the Visual C++ node, then select Windows Forms Application in the Templates pane.
3. Enter the solution name and location and click OK.
4. Now drag three labels, a Datetimepicker and a button control from the tool box.
5. Set The name of the form by clicking the Text property of form as “Date chooser”
6. Set the text of the label as “Choose a date”, Visibility as true. Place this label just before the datetime picker.
7. Place the other two labels just below the first label and the datetime picker and set the visibility as false.
8. Set the text of button as “Done”.
9. Write the following code for the button click event:

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Application::Exit();
}

10. Now, add a value cahnged event for the date time picker


private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e)
{
label2->Visible =true;
label3->Visible = true;
label3->Text = String::Format("new date : {0}",dateTimePicker1->Text);
}
11. Now Build the solution and run it without debugging.
12. The new Windows Form is displayed in the desired format.


Complete Program:


#pragma once

namespace FirstWindowsFormsApplication {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///

public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///

~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label1;
protected:
private: System::Windows::Forms::DateTimePicker^ dateTimePicker1;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private:
///
/// Required designer variable.
///

System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

void InitializeComponent(void)
{
this->label1 = (gcnew System::Windows::Forms::Label());
this->dateTimePicker1 = (gcnew System::Windows::Forms::DateTimePicker());
this->button1 = (gcnew System::Windows::Forms::Button());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast(0)));
this->label1->Location = System::Drawing::Point(1, 71);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(91, 13);
this->label1->TabIndex = 0;
this->label1->Text = L"Choose a Date";
//
// dateTimePicker1
//
this->dateTimePicker1->Location = System::Drawing::Point(109, 67);
this->dateTimePicker1->Name = L"dateTimePicker1";
this->dateTimePicker1->Size = System::Drawing::Size(200, 20);
this->dateTimePicker1->TabIndex = 1;
this->dateTimePicker1->ValueChanged += gcnew System::EventHandler(this, &Form1::dateTimePicker1_ValueChanged);
//
// button1
//
this->button1->BackColor = System::Drawing::SystemColors::GradientInactiveCaption;
this->button1->Location = System::Drawing::Point(109, 165);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 2;
this->button1->Text = L"Done";
this->button1->UseVisualStyleBackColor = false;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(12, 118);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(97, 13);
this->label2->TabIndex = 3;
this->label2->Text = L"You have choosen";
this->label2->Visible = false;
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(115, 118);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(35, 13);
this->label3->TabIndex = 4;
this->label3->Text = L"label3";
this->label3->Visible = false;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::Info;
this->ClientSize = System::Drawing::Size(318, 273);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->button1);
this->Controls->Add(this->dateTimePicker1);
this->Controls->Add(this->label1);
this->Name = L"Form1";
this->Text = L"Date Time chooser";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Application::Exit();
}


private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e)
{
label2->Visible =true;
label3->Visible = true;
label3->Text = String::Format("new date : {0}",dateTimePicker1->Text);
}
};
}

Most of the code here is sytem generated.The code in italics is the only code written by me. :)

Declaration:
All credits to msdn.

mail to : archita.dash@rediffmail.com

Understanding VC++.NET -1st Installment

1. C++ is a strongly typed language.
2. It is an efficient language.
3. It is an object-oriented language.
4. It is based on C.
5. Is case sensitive.
6. Golden rule of C++ is everything must be declared before being used.
7. With Visual C++ Express Edition, you can create Visual C++ .NET projects, including Windows Forms applications. You can also create C and C++ programs that conform to ANSI and ISO standards.

HelloWorld program in VC++.NET

// HelloWorld.cpp : main project file.

#include "stdafx.h" //copy in the file named "stdafx.h" at the begining of the program

using namespace System;

int main(array ^args)
{
Console::WriteLine(L"Hello World");
return 0;
}

Native C++ Program from the Command Line


1. Open the Visual Studio 2005 Command Prompt window.
2. At the command prompt, type notepad .cpp and press Enter.
3. In notepad type
#include

int main()
{
std::cout<<"This is a native c++ program." <<
C++ Program with .NET Classes with Command Prompt Compilation

1. Open the Visual Studio 2005 Command Prompt window.
2. At the command prompt, type notepad .cpp and press Enter.
3. In notepad type

int main ()
{
System: Console::WriteLine ("Hi, How are you”)
}

4. On the File menu, click Save. You have created a C++ source file.
5. On the File menu, click Exit to close Notepad.
6. At the command line prompt, type cl /Clr .cpp and press Enter.
(EH is the error handler routine.)
7. To see a list of all files in the directory named simple with any extension, type dir .* and press Enter.
8. To run the .exe program, type and press Enter.
9. The program displays this text and exits.

Note: The .Net class used here is Console from the namespace “System”.

Program 1: Creating a Text File Using Visual Studio and VC++.NET


1. Create a new VS 2005 project in VC++

2. Select CLRàSelect CLR empty Project.
3. Enter the solution name and location and click OK.
4. Right click the source folder and click on “Add Item”
5. In “Add Item”, select C++ File.cpp.
6. And write the following code:
using namespace System;
using namespace System::IO ;

int main()
{
String^ FileName = "TextFile.txt";

StreamWriter^ sw = gcnew StreamWriter(FileName);

//gcnew is used instead of new in c#
//^ is equivalent to a pointer as * in c#

sw->WriteLine("Hi! Archita!");
sw->WriteLine("You are creating a text file");
sw->WriteLine("To use it for write or writeline purpose");
sw->WriteLine("You can use this for {0} also" ,"formated output");
sw->WriteLine(DateTime::Now);
sw->Close();
Console::WriteLine(" You are using the file {0}to write",FileName);

return 0;

}
Note: The thing which I found most difficult in this exercise was to get the name of classes, properties and methods using “::” being a c# programmer I have got very comfortable with using “.” …I hope to get acquainted with “::” soon. J


7. Now build the solution using f7 key. Once the project is built now you can start the program by choosing “Start Without debugging”.

8. The text file is written on the same location as the project is:


Hi! Archita!
You are creating a text file
To use it for write or writeline purpose
You can use this for formatted output also
5/29/2007 5:08:37 PM



Declaration :
I am creating this post basically for my own reference while reading VC++.NET.
Many of the programs reffered here may resemble to the VC++.NET SDK.
I take no credit on saying that these are original programs written by me.


Sunday, May 27, 2007

Creating a .NET Windows Service using .NET3.0


1. Definition of a windows service?

Windows service is any application which starts when the computer boots up irrespective of the user. In UNIX it is called a demon process. Once a windows service is installed it can be modified using the Administrative Tool of Control Panel.
Windows Provides a Service Control Manager which controls the start, stop, pause of any given service.
Windows Service by default are run on a virtual user. “Local Service that has administrative rights on the system. The working directory will be the Windows system directory (typically C:\WINNT) and the default temp directory will typically be C:\WINNT\TEMP.
Windows services can be set up to run as any user although running as a user other than the default requires storing a password. It is important to consider that as soon as the password is changed, the service will not run unless the password provided for the service is also changed.
So, it is always preferred to use a default user for windows services, until and unless required.

2. Difference between a normal windows application and a windows service?

If an application is developed which can serve other applications it becomes service.
In the sense say if u own a Travel House and u r having app which displays rate and availability of buses on selected date. Since its limit is within your work area it is an application. But if u designed the same in such a way that it can be used by any Travel Company to design an app. which will use that info and service their clients your app becomes service.
Windows services is different from normal windows application in the sense that for windows application an exe file is enough to install but when it comes to windows services the it is installed by the utility provided by .Net called InstallUtil.exe or an MSI installer.


3. Basic points regarding windows service

a. Windows service can run without a user context.
b. Windows services are generally started when the computer boots up and can be
Started, stopped, paused, and restarted, from the services applet.
c. Windows Services can be managed programmatically and more easily in .NET using the
ServiceController component.
d. User messages are typically written to the Windows Event Log.

4. Creating a .NET Windows Service:

The service we will create does nothing really useful other than serve as a demonstration.

When the service is started we will just log relevant data in a text file at a particular location.

Following steps should be followed in order to create a service:

1. Start Visual Studio .NET and create a new project. Choose C# Project and Windows application.

2. Right Click on “MyService” and click on “Add New Item.”
3. In “Add New Item “window select “Windows Service” and name it “MyService” and click add.
4. Delete Form1.cs and Program.cs so as it is not required, so that the solution explorer looks like.
5. The Code looks something like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;

namespace MyService
{
partial class MyService : ServiceBase
{
public MyService()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
}

protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
6. Drag and drop timer to your service design view.
Note: Choose timer from components menu and not from Windows forms.

5. Adding Functionality to the service:

Add the following functionality to your service:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.IO;



namespace TryingWindowsService
{
partial class MyService : ServiceBase
{
public MyService()
{

InitializeComponent();
}

#region Main
static void Main()
{
System.ServiceProcess.ServiceBase[] ServiceToRun;
ServiceToRun = new System.ServiceProcess.ServiceBase[]
{
new MyService()
};
System.ServiceProcess.ServiceBase.Run(ServiceToRun);
}
#endregion Main


#region start
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
this.timer1.Enabled = true;
FileStream fs = new FileStream(@"d:\temp\windowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter streamwriter = new StreamWriter(fs);
streamwriter.BaseStream.Seek(0, SeekOrigin.End);
streamwriter.WriteLine("WindowsService : ServiceStarted\n");
streamwriter.Flush();
streamwriter.Close();
}
#endregion start


#region Stop
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
this.timer1.Enabled = false;
FileStream fs = new FileStream(@"d:\temp\windowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter streamwriter = new StreamWriter(fs);
streamwriter.BaseStream.Seek(0, SeekOrigin.End);
streamwriter.WriteLine("WindowsService : ServiceStopped\n");
streamwriter.Flush();
streamwriter.Close();
}
#endregion stop

}
}
6. Add Windows Installer to the service

1. To add windows installer service right click on the designer view and then click on “Add Installer” and name the file “MyServiceInstaller”
2. Add the following lines of code to “MyServiceInstaller”:
this.MyServiceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this. MyServiceInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

3. The installer code looks like:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;

namespace MyService
{
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
}
}
}

4.Build the application


7. Installing the Windows service:

1. Open Visual Studio.NET command prompt
2. Change to bin\Release folder of the project
3. Issue the command InstallUtil.exe MyService.exe to register the service and have it create the appropriate registry entries :
InstallUtil.exe MyService.exe

4. Open the computer managementàServicesàand Check for the program is running.

5. To uninstall the service use the command:
InstallUtil.exe /u MyService.exe
For more information:
http://www.theserverside.com/discussions/thread.tss?thread_id=17304
http://msdn.microsoft.com/msdnmag/issues/01/12/NETServ/
http://en.wikipedia.org/wiki/Windows_service

Points To Ponder:
1. You can set the CanStop property for a service to false. This renders the Stop command unavailable on that particular service; if you try to stop the service from Server Explorer, the necessary menu item appears dimmed. If you try to stop the service from code, the system raises an error: "Failed to stop "
In case of doubts and clarification please feel free to mail at: archita.dash@rediffmail.com