What is the difference between Class and Structure?

Answer Posted / ashish agarwal

1. Classes are reference types and structs are value types.
Since classes are reference type, a class variable can be assigned null.But we cannot assign null to
a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct ( but dealing directly with them ).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs.But classes can have
example:class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors. But structs cannot have
7. Classes must be instantiated using the new operator. But structs can be
8. Classes support inheritance.But there is no inheritance for structs.
( structs don’t support inheritance polymorphism )
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.11. A class is permitted to declare a destructor.But a struct is not
12. classes are used for complex and large set data. structs are simple to use.

Is This Answer Correct ?    0 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How do you find out if a linked-list has an end? (I.e. The list is not a cycle)

607


What are the manipulators in c++?

555


What is the full form of c++?

623


What is a dangling pointer in c++?

666


What is c++ map?

573






What is the purpose of the "delete" operator?

628


What is a dll entry point?

567


What is input operator in c++?

591


Write a program for Divide a number with 2 and Print the output ( NOTE: Check for divide by zero error).

638


In what situations do you have to use initialization list rather than assignment in constructors?

643


What is a buffer c++?

588


What is the role of C++ shorthand's?

683


Differentiate between an external iterator and an internal iterator? What is the advantage of an external iterator.

621


Why is c++ difficult?

618


Specify some guidelines that should be followed while overloading operators?

625