answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

Is NET in support of object oriented language?

Yes, every language supported by Microsoft and on the .NET framework is an object oriented language. (OOP)

Why is C plus plus called an object oriented programming language?

Any language that supports class types, private and protected data, inheritance, polymorphism, function overriding, virtual methods is regarded as an object oriented programming language. However, while C++ supports OOP, it does not rely on it. You can mix C++ and C-style code (non-OOP) in the same program.

What is difference between c plus plus and data structures?

Data structure is nothing but a way to organize and

manipulate any given set of data in a specific and reusable

format/structure hence simplifying the manipulation of data.

Some of the commonly and frequently used data structures

are Stack, Queue, List, Set, e.t.c. But this list is not

limited to what we see here, rather we can invent our own

as long as there is a definite structure and better

efficiency by using it than work with raw data.

What are classes and objects in Cpp?

A class is the definition of an user-defined type while an object is an instance of a class.

class foo {}; // definition of a type (implementation omitted for brevity).

struct bar {}; // another definition of a type

foo x; // x is an instance of the foo class, therefore x is an object

bar y; // y is an instance of the bar class, therefore y is an object

Note that in C++, struct and class are exactly the same (they are both classes), the only difference being that members of a class are private by default while members of a struct are public by default. Thus the following definitions are exactly the same:

struct X {

Y(){} // public by default

};

class Y {

public:

X(){} // public by specification

};

As are the following:

struct A {

private:

int m_data; // private by specification

};

class B {

int m_data; // private by default

};

What is different between object and variable in c plus plus?

A variable is simply a named value where the value is not constant -- meaning it can be changed at any time.

A pointer is a variable (or a constant) that can store a memory address and provides indirect access to that memory address. It is called a pointer because it is said to "point to" the memory address it contains. A pointer that doesn't actually point at anything should store the value zero (represented by the constant NULL). When you allocate memory dynamically, you must maintain at least one pointer to that memory in order to release the memory back to the system, which is achieved by deleting the pointer, and then nullifying the pointer, or pointing it to another allocation. Pointers can also be typed, such that the memory address being pointed is treated as if it were that type, thus a pointer to a char can be used to determine the value of each individual byte in a multi-byte value, such as an int, simply by incrementing its stored address to traverse the individual bytes. By the same token an array of 4 bytes can be treated as if it were a single 32-bit value, simply by pointing at the first byte using a pointer with type int. Note that a pointer can only physically point at one byte at a time, but its type allows you to access one or more contiguous bytes according to its type, thus incrementing the pointer's stored address will advance the pointer by the size of its type. Thus a pointer to int will automatically increment (or decrement) by sizeof(int) bytes.

Pointers can also point at other pointers, adding extra levels of indirection. This is most useful when you need to pass a pointer to a function by reference, since all pointers are always passed by value. However, passing a pointer to a pointer is the same as passing the pointer being pointed at by reference, which allows the pointer itself to be manipulated, not just what it points at. Pointer to pointer types are also useful when allocating large dynamic arrays as they allow the array to be allocated non-contiguously as a series of smaller, separate arrays. This uses more memory overall, but allocating many smaller arrays is far more likely to succeed where a large contiguous allocation could easily fail if a large enough block of free memory is not available.

Is there any program used to create c plus plus program?

There are several: an editor, a compiler and linker being the three main programs. Typically you will install an integrated development environment (IDE) that includes all three plus project management and debugging utilities, help compilers, installation helpers, and a raft of plug-ins to suit the platform you are developing for.

What is the use of iostream in c plus plus programming?

iostream.h is deprecated and should not be used. It was originally shipped with early versions of C++ which used CFront to produce C compatible code from C++ source. Later, when C++ was standardised, iostream.h became iostream (without the .h extension), but many implementers shipped with both versions. However, iostream.h is not standards compliant and should not be used today. In most cases the file can simply be deleted unless you have non-compliant legacy code that requires it.

What is friend class in c plus plus?

A friend class is any class that is granted access to the private members of another class. The following minimal example demonstrates a simplistic friend class.

#include<iostream>

class A {

friend class B;

public:

A(int data=0):m_data(data){}

private:

int m_data;

};

class B{

public:

B(const A& a):m_data(a.m_data){}

int getdata()const{return(m_data);}

private:

int m_data;

};

int main()

{

A a(50);

B b(a);

std::cout<<b.getdata()<<std::endl; // prints 50

return(0);

}

In the above example, A's encapsulation is such that A:m_data can be initialised through A's constructor but is otherwise inaccessible outside of the class. The assumption is that the A::m_data is intended for internal use only. However, B's encapsulation is such that it can be constructed from an instance of A, but since there is no public accessor to A::m_data, B requires friend access to A, and only A can grant that access, hence class B is declared a friend of A.

Note that friends can be declared any where in a class declaration since private, protected and public access do not apply. Note also that there is no need for a forward declaration of B before declaring A because B is dependant upon A, not A upon B.

It should also be noted that although B could potentially undermine the encapsulation of A (a common complaint where friends are concerned), the assumption is that since you are in control of both A and B, then it is your responsibility to ensure that B obeys the same encapsulation rules you set out within A. That is, if A provided a private A::getdata() accessor and a corresponding A::setdata() mutator for its own internal use, then B should make use of that same accessor and mutator rather than access A::m_data directly. This ensures that should you alter the implementation of A::m_data, you will not affect the inner workings of B, thus enforcing A's encapsulation rather than undermining it, and therefore minimising maintenance.

Friend classes are often used wherever two classes work closely together. For instance, a parent and child class often work in tandem, thus it can often make sense to for the child class to declare the parent class a friend. However, there are often better ways than declaring an entire class to be a friend of another class. Friend functions (which can include specific class methods) greatly reduce the chances of undermining encapsulation by limiting the exposure of your private class members. Thus instead of declaring the entire parent class to be a friend of the child class, you could simply declare specific functions to be friends of both classes, thus those functions provide the "glue" that binds the two classes together.

Undermining encapsulation is always a danger with friends, thus you should never grant friendship unnecessarily. After all, the onus is upon you to enforce your own encapsulation rules -- the compiler cannot help you any more than it can help you enforce those rules within the class itself. However, if the public interface is sufficient for your needs, then you do not need friends. You should only use friends when the public interface is insufficient and where altering the interface to suit would actually do far more to undermine the encapsulation than a friend would.

What is static in c plus plus programming?

The keyword "static" in C has a slightly complicated meaning, depending on where it is used. It generally denotes static storage, meaning that it is allocated in the static data area of the program, and not on the stack or heap. Also, it generally limits the visibility of the name to a certain area of the code.

If used on a variable or function of global scope, then it generally means that the function or variable can only be used by other functions within the same file, as opposed to "extern" which means that the variable and function can be used from other files.

If used on a local variable within a function, it means that the variable maintains its value between function calls (since it is allocated statically and not on the stack).

Cpp program for quick sort?

//Quicksort the array

void quicksort(int* array, int left, int right)

{

if(left >= right)

return;

int index = partition(array, left, right);

quicksort(array, left, index - 1);

quicksort(array, index + 1, right);

}

//Partition the array into two halves and return the

//index about which the array is partitioned

int partition(int* array, int left, int right)

{

//Makes the leftmost element a good pivot,

//specifically the median of medians

findMedianOfMedians(array, left, right);

int pivotIndex = left, pivotValue = array[pivotIndex], index = left, i;

swap(array, pivotIndex, right);

for(i = left; i < right; i++)

{

if(array[i] < pivotValue)

{

swap(array, i, index);

index += 1;

}

}

swap(array, right, index);

return index;

}

//Computes the median of each group of 5 elements and stores

//it as the first element of the group. Recursively does this

//till there is only one group and hence only one Median

int findMedianOfMedians(int* array, int left, int right)

{

if(left == right)

return array[left];

int i, shift = 1;

while(shift <= (right - left))

{

for(i = left; i <= right; i+=shift*5)

{

int endIndex = (i + shift*5 - 1 < right) ? i + shift*5 - 1 : right;

int medianIndex = findMedianIndex(array, i, endIndex, shift);

swap(array, i, medianIndex);

}

shift *= 5;

}

return array[left];

}

//Find the index of the Median of the elements

//of array that occur at every "shift" positions.

int findMedianIndex(int* array, int left, int right, int shift)

{

int i, groups = (right - left)/shift + 1, k = left + groups/2*shift;

for(i = left; i <= k; i+= shift)

{

int minIndex = i, minValue = array[minIndex], j;

for(j = i; j <= right; j+=shift)

if(array[j] < minValue)

{

minIndex = j;

minValue = array[minIndex];

}

swap(array, i, minIndex);

}

return k;

}

//Swap integer values by array indexes

void swap(int * array, int a, int b)

{

int tmp = array[a];

array[a] = array[b];

array[b] = tmp;

}

What is the difference between object-oriented and procedural programming?

Procedural programming can sometimes be used as a synonym for imperative programming. To a programming paradigm based upon the concept of the procedure call. Procedures, also known as routines, subroutines, methods, or functions (not to be confused with mathematical functions, but similar to those used in functional programming) simply contain a series of computational steps to be carried out. Any given procedure might be called at any point during a program's execution, including by other procedures or itself. The important features of Procedural Programming. 1. Programs are organized in the form of subroutines and all data items are global. 2. Program controls are through jump(goto) and calls to subroutines 3. Subroutines are abstracted to avoid repetitions. 4. Suitable for medium sized software application 5. Difficult to maintain and enhance the program code. K E Narayana

When destructor can be virtual in c plus plus?

A class constructor initialises object member variables, ensuring the object is in a valid state from the point of instantiation. The destructor resets those same variables when the object falls from scope. Typically, the destructor is only required to release any memory allocated to any internal class pointers.

What is data type in c plus plus?

A data type simply means the type of data represented by a variable or constant, or the return type of a function. C++ is a strongly-typed language thus all variables and constants must have a data type associated with them. The data type may be a primitive data type such as int or char, which are used as the building blocks for more complex data types. Primitives, typedefs, enums and classes (which includes structs and unions), are used to provide the definitions for all the various data types that you can employ within a program. Variables and constants provide instances of those data types. Pointer variables must also have a data type associated with them to determine the type of data being referred to, even if it is void* which simply means it points to any data type, the actual data type being determined at runtime. However, in C++, void* is rarely required since polymorphism allows programmers to treat objects generically; there is rarely a need to know the actual runtime type of an object, since that information is provided automatically by the object's own virtual table. The programmer need only know the generic data type and call the appropriate virtual methods of that type in order to invoke the specific behaviour of the actual data type.

What is the for loop in c plus plus?

In C, also in C++, the for loop executes zero or more times, until the test expression is false...

for (init-expression; test-expression; loop-expression) statement;

/* init-expression executed once, at beginning */

/* statement executes zero or more times, until test-expression is false, test first */

/* loop-expression evaluated at end of each iteration */

How many bytes in long?

The set of datatypes and the definition of each member is dependent on hardware, the language standard, and the language implementation. Not knowing which language the question relates to is particularly limiting.

In Java, a long consists of 8 bytes. This is also generally true for C and C++, depending upon the compiler used. See the related links for further details.

Why is C plus plus such a robust programming language?

Borland's implementation of C++ was never regarded as the Bible of Computer Programming (whatever that means). If it were we'd probably still be using it today, but it was rendered obsolete in 1997 when Borland C++ Builder superseded it.

What is difference between constant in c plus plus and final in java?

The final keyword can be used to modify a class, method, or variable.

When used on a variable, it means that variable cannot be changed once set.
When used on a method, it means that no subclasses may override that method.

How can you pass variable arguments to a function in c?

## posted BY Pulkit ok. so to declare variable argements in arguments use this: ret_type function_name( . . .); using these three dots will tell compiler to include variable aarguments. Note: this feature has been included in New version of C,, this is not available in old compiler. thankx guys n grls ## posted BY Pulkit ok. so to declare variable argements in arguments use this: ret_type function_name( . . .); using these three dots will tell compiler to include variable aarguments. Note: this feature has been included in New version of C,, this is not available in old compiler. thankx guys n grls

Write a program in c plus plus to compute the factorial of a given number?

// Name: A User-Defined Function to find Factorial of a Given// Number

#include

#include

void main()

{

int n;

long f,fact(int b);

clrscr();

printf("\n\n\t Enter a Number(B/W 0 to 31)::");

scanf("%d",&n);

if(n>=32)

{

printf("\n\t Enter a number between 0 to 31");

exit 0;

}

f=fact(n);

printf("\n\t The Factorial of %d is %ld",n,f);

getch();

}

long fact(int b)

{

int i;

long f=1;

for(i=1;i<=b;i++)

{

f=f*i;

}

return f;

}

How do you implement a stack using an array in c plus plus?

An array in C++ is fixed-size and is unsuitable for implementing stacks. You can use a C-style dynamic array, of course, but the C++ method is to use a vector. A vector encapsulates a C-style dynamic array along with its size and greatly simplifies the way you work with arrays.

Dynamic arrays are generally the best way to implement a stack, however be aware that when the array is full and you want to add a new element, you must reallocate the array which can occasionally cause the entire array to be moved to new memory. A vector, on the other hand, automatically reserves 1.6 times the consumed memory on each reallocation and thus minimises the need to reallocate.

Vectors provide a push_back() and pop_back() method, since these are the fastest methods of inserting and extracting elements from an array (inserting or extracting anywhere else would result in elements being shunted up and down the array, which is inefficient). These two methods alone are all you need to implement a stack. However, vectors also permit random access to any element within the array. To eliminate all unnecessary features, you must encapsulate the vector within an adaptor class (a thin-wrapper) that only exposes the functionality you actually need. A minimal implementation is presented here:

#include<vector>

template<typename T>

class stack

{

std::vector<T> m_data;

public:

stack() =default;

~stack() =default;

stack(const stack&) =default;

stack(stack&&) =default;

stack& operator= (const stack&) =default;

stack& operator= (stack&&) =default;

void push (const T& data) {m_data.push_back (data);}

void pop () {m_data.pop_back ();}

T& top () {return m_data.back();}

const T& top () const {return m_data.back();}

};

This is fairly similar to the way a std::stack is implemented in the STL, although it also provides specialisations for pointer types. For more information on the implementation, consult the <stack> header in the standard library.

What types of functions cannot be made virtual?

Static member functions, member function templates and constructors cannot be virtual.

Which program can you use to write C Plus Plus scripts?

You can use any text editor you want, say notepad in windows and vi in unix. You can also use MS Word, but you need to save in text format, i.e. with no formatting, because the compiler only understands the text, and not the formatting.

Often, however, the text editor is part of an integrated development environment, that makes it easier to highlight code and errors, organize classes and modules, and to debug visually. In the Windows environment, that might be Visual Studio, but it can be any supported product for your platform.

How do you write a C program to print the diagonal element of a NxN matrix?

#include<stdio.h>

#include<conio.h>

void main()

{

int a[3][3],b[3][3],c[3][3],r,c;

for(r=0;r<=3;r++)

{

for(c=0;c<3;c++)

{

printf("\n enter the value=");

scanf("%d%d",&a[r][c],&b[r][c]);

}

}

printf("\n first matrix=\n");

for(r=0;r<=3;r++)

{

for(c=0;c<3;c++)

{

printf("%d\t",a[r][c]);

}

printf("\n");

}

printf("\n scond matrix=\n");

for(r=0;r<=3;r++)

{

for(c=0;c<3;c++)

{printf("%d\t",b[r][c]);

}

printf("\n");

}

printf("\n sum of given matrix=\n");

for(r=0;r<=3;r++)

{

for(c=0;c<3;c++)

{

c[r][c]=a[r][c]+b[r][c];

printf("%d\t",c[r][c]);

}

printf("\n");

}

getch();

}

What do you mean by inheritance . give example from c plus plus?

Inheritance in C++ is where you derive a new object from an existing object. The derived object is simply a more specialised version of the original object. The existing object could be a generic car object from which we could derive a more specific type of car such as the Aston Martin DB9. Moreover, if we have a DB9 object then we could just as easily derive an even more specific DB9 such as the Aston Martin DBR9.

In other words, the DB9 inherits all the properties that we might associate with a car, such as a chassis, 4 road wheels, a steering wheel, an engine and gearbox, and a body. By the same token, the DBR9 inherits all the properties of a DB9 (and therefore all the properties of a car), retaining the chassis, engine block and cylinder heads from the DB9 whilst adding high performance components elsewhere.

This is, of course, an over-simplification. But when we model the real-world within a computer we never model the real-world in minute detail, we only model part of the real-world (and usually just a minuscule part of it), and only in as much detail as we need in order to solve a problem. For instance, if we wished to model traffic flow through a city, we don't necessarily need to know how many DB9s are passing through. That "a car" passed through is probably all we need to know. But that car could be derived from a more generic "road-vehicle" object, which would then allow us to model buses, trucks, motorbikes and push bikes.

When modelling the real-world it's important to identify early on which objects are real and which are purely conceptual. In our DB9 example, the car object is best described as being a purely-conceptual object -- an abstraction -- but in our traffic flow model that same car could be a real object. Or it could be conceptual if we wished to distinguish between petrol, diesel, electric and hybrid cars.

In C++ there are several inheritance models. Single inheritance is fairly straightforward and describes how one type of object is directly derived from another type of object. When discussing the type of an object we are referring explicitly to its class, and it is the class that defines the type of inheritance.

Multiple inheritance describes how one class is directly derived from two or more distinct classes. You might use this type of inheritance when describing a hybrid car, since it is derived from both a petrol and an electric car. Or an amphibious landing craft which is both a car and boat.

Multi-level inheritance occurs when a generic class is also a derived class. In our DB9 example, the DB9 is generic with respect to the DBR9, but also derived with respect to the car. Most of the time this is of little concern since the derived object is only really concerned with the generic class or classes from it was directly derived. However, occasionally it leads to an inheritance model that can sometimes be problematic if not handled correctly: virtual inheritance.

Virtual inheritance describes the way in which a derived object inherits from two or more generic objects, and those generic objects are themselves derived from a common generic object. Going back to our hybrid example, we can see how this works in the real-world. Our hybrid car obviously inherits from both a petrol and an electric car, but both of these could inherit from the generic car. The problem is that this means there are two instance of the generic car within our hybrid, but the hybrid is just one car. When we refer to the car class directly from our hybrid, there is ambiguity because there's no way to determine which instance of car we are actually referring to. Virtual inheritance gets around this ambiguity by allowing both petrol and electric cars to inherit from car virtually, rather than directly.

What this means is that our hybrid (and any derivative of hybrid) inherits directly from one instance of car, while our electric and petrol cars both share this one instance, virtually. An electric car, by itself, will still inherit directly from car, as will a petrol car, since they are both the most-derived classes in those specific models, but our hybrid or any derivative of hybrid renders the car a virtual class. With only one instance of car, all ambiguity is removed.

Now that we've discussed how inheritance works in principal, we can examine

the ways in which we can modify access to the generic class members with respect to the derived class. Inheritance may be done with private, protected or public access. When not explicitly stated, the default is private access for classes and public access for structs (exactly the same as would apply to the class member access specifiers). Regardless of the access specified via inheritance, derived classes always inherit all the public and protected members of their generic classes. All we're really doing is modifying their visibility with respect to the derived class. However, private members of the generic class are never inherited, and we can never elevate access, we can only keep it the same, or reduce it. Any member with greater access to the specified access will be reduced to the specified access. Thus if we specify public access, all generic members maintain their current access. If we specify protected access, all public members of the generic class become protected members of the derived class. And with private access, all public and protected members become private members of the derived class.

Normally we will alter the access via the inheritance declaration itself, which applies to the generic class as a whole. However, we can also modify the access to individual members, simply be redeclaring them with the new access type, thus giving us fine granular control over every public and protected member that is inherited.

The following code examples demonstrate some of the principals thus far described.

class A {};

class B : public A {}; // single inheritance

class C : public B {}; single-inheritance, multi-level

class D : virtual public C {}; virtual single inheritance, multi-level

class E : virtual public C {}; virtual single inheritance, multi-level

class F: public D, public E {}; virtual multi-inheritance, multi-level

All these examples are non-functional since the declarations have been left empty. However, they describe the bare essentials required of inheritance. All access to the generic classes is declared public, so there would be no changes to how the base class members are accessed with respect to the derived class.

Most classes that are intended to act as generic classes will include one or more virtual methods (virtual functions). This simply means that derivatives are expected to override those methods as required in order to provide a more specific implementation. If the generic implementation suffices, there is no need to override it. However, it's important to remember that if there is one or more virtual functions in the generic class, the generic class destructor must also be virtual.

When a generic class is intended to act as a conceptual class or an abstract data type, then it must have at least one pure-virtual method. What this means is that the derived class must override all pure-virtual methods otherwise it becomes an abstract class itself. Once a derivative implements an override, that override reverts to being a virtual method which can subsequently be inherited, even if the the derived class remains abstract. The generic abstract class may or may not provide implementations for its pure-virtual methods, but any that are provided cannot be inherited (only the signature is inherited), and can only be called explicitly via a derived class override. Note that abstract base classes cannot be instantiated by themselves -- remember they are conceptual objects, not actual objects. They can only be instantiated through inheritance and only by providing (or inheriting) a complete implementation of the abstract interface.

To understand abstraction, consider a shape object. There is no such thing as a shape, there are only types of shape. Thus a shape is the concept of an object, whereas a circle, square or triangle are the physical embodiment of shape objects, and therefore inherit all the properties of shape; everything that is common to all shapes such as vertices, colour, a bounding rectangle (which is itself a shape), and so on. To use another analogy, a mammal is a conceptual object whereas a Golden Labrador is a specific type of mammal. Depending on the amount of detail you require in your model, a dog could be considered an actual object if you weren't interested in specific types of dogs, or conceptual if you were. If you were only interested in mammals and reptiles, then animal objects would be considered conceptual. And so on.