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

What is static variable in the class in cpp?

Static member variables of a class are variables that are local to the class within which they are declared. That is, each instance of the class (each object) shares the same common member variable. Changing that variable's value in one instance will change it for all instances.

Contrast with a non-static member variable where each instance of the class has its own independent variable, scoped to the object itself (not the class of object).

Where does global variables stored in C?

It depends entirely on what platform you are using.

In an embedded environment, for instance

global/static variables go into different RAM memory segments depending on whether or not they are initialised.

constants are often left in ROM

automatic variables are normally placed of the stack of the currently running task but not always.

How to remove duplicate values in an array?

The simplest way of doing this is not very efficient, but provides a quick development time. You want to take all of the elements of the array, add them to a Set, then retrieve them as an array again. Note that this will probably not preserve the order of elements in the array.

{

Object[] originalArray; // let's pretend this contains the data that

// you want to delete duplicates from

Set newSet = new HashSet();

for (Object o : originalArray) {

newSet.add(o);

}

// originalArray is now equal to the array without duplicates

originalArray = newSet.toArray();

}

Now the efficient, and more correct, solution.

This one will create a new array of the correct size without duplicates.

{

Object[] originalArray; // again, pretend this contains our original data

// new temporary array to hold non-duplicate data

Object[] newArray = new Object[originalArray.length];

// current index in the new array (also the number of non-dup elements)

int currentIndex = 0;

// loop through the original array...

for (int i = 0; i < originalArray.length; ++i) {

// contains => true iff newArray contains originalArray[i]

boolean contains = false;

// search through newArray to see if it contains an element equal

// to the element in originalArray[i]

for(int j = 0; j <= currentIndex; ++j) {

// if the same element is found, don't add it to the new array

if(originalArray[i].equals(newArray[j])) {

contains = true;

break;

}

}

// if we didn't find a duplicate, add the new element to the new array

if(!contains) {

// note: you may want to use a copy constructor, or a .clone()

// here if the situation warrants more than a shallow copy

newArray[currentIndex] = originalArray[i];

++currentIndex;

}

}

// OPTIONAL

// resize newArray (using _newArray) so that we don't have any null references

String[] _newArray = new String[currentIndex];

for(int i = 0; i < currentIndex; ++i) {

_newArray[i] = newArray[i];

}

}

---------

The second version is correct in theory. However, if you deal with large two- or more- dimensional arrays, you are in trouble, as with each new element in the destination array you will have to search through a greater number of elements.

This is especially true if you look for duplicates in more than one element of the array, for example looking in columns 'a' and 'b' of array

a1 b1 c1 d1

a2 b2 c2 d2

a3 b3 c3 d3

Drop in performance is unbelievable if you go over approx 1,000 records with majority or records being unique.

I am trying to test a couple of different approaches for large arrays. If anyone is interested, let me know, and I will keep you posted.

What is ide in c plus plus .explain?

There is no single answer to this since everyone has their own opinion on what is the best IDE. For example, a Windows programmer will probably advocate Borland/Embarcadero C++ Builder or Microsoft VC++, while a Linux programmer might favour a more generic implementation such as GC++, which is better suited to cross-platform coding.

When would you use overloading in C plus plus?

A function overload is a function that has more than one implementation. Each implementation must have a unique function signature, only the name remains the same, however functions cannot differ by return type alone.

Many overloads can be implemented as template functions, where the only difference is the type or types being operated upon. Manual overloading is typically required when the number of arguments differ. Generally, we try to implement function overloads such that one overload provides the implementation for the general case, while all others are expressed in terms of the general case. Where this may result in a loss of efficiency, we generalise as much as is possible and provide a limited number of specialised implementations to cater for exceptional cases.

As a typical example, to find the largest of any two values of the same type, regardless of the type, we can use a template function:

template<typename T>

const T& largest (const T& a, const T& b) {

return a>b?a:b;

}

This function provides the general case. From this we can provide specialisations, such as an overload to cater for three arguments which can be expressed directly in terms of the general case:

template<typename T> const T& largest (const T& a, const T& b, const T&c) {

return largest (largest (a, b), c);

}

Difference between C and C Plus programming languages?

C++ allows you to mix object oriented programming with generic programming and C-style programming. C has none of these features.

C-style programming and C programming are broadly similar, with only minor differences, most of which are irrelevant. As such, it is very rarely necessary to use a lower-level language than C++.

The static type system in C is inherently weak; filled with loopholes and inconsistencies. C++ is much more robust by comparison.

What is an interface class and what is an abstract class?

The term interface class does not exist in C#. If this is a term describing a class being an interface to other component (human, subsystems, etc), it is very application specific. The designer of that application should know the abstraction.

However, C# does have another type called interface. An interface is NOT a class. An interface defines the intention of some behaviors that classes may be extended it and provides the implementation. The intention, is nothing but method signatures, which defines the return data type, the method name, and any method arguments and associated data type. The implementation is the code of the method. Interface is used for separating the concern of design and implementation.

Abstract class is a class with abstract keyword. It can be just like a class without that keyword (then, why it is an abstract class?). But it may have some methods or properties defined as abstract. These abstract methods, like the method signatures of an interface, defines the intention.

The subclasses of such an abstract class would need to implement those abstract methods (providing the code).

There are more common, differences between interfaces and abstract classes, please see answer(s) of those related questions in C# category.

What is self referential function in c plus plus?

A self-referential function in C++, or in any other supporting language, is a recursive function.

Why you cannot pass arguments to destructor in C programming?

A more pertinent question is why would you need to? The destructor exists purely to clean up any memory allocated to the class instance variables. If the destructor requires a "parameter" to do so, then there's a clear design flaw in the class. The class is perfectly capable of cleaning up its own instance variables without any need for a parameter.

What is push operation in data structure?

Push inserts a value onto the top of the stack.

Pop extracts the top value from the stack.

These are the two primary operations that can be performed upon a stack. Prior to popping a value, you will first check the stack is not empty, store the top value, then pop the stack. For a stack of type T, you might use the following:

if (!stack.empty()) {

T value {stack.top()}; // copy top value

stack.pop(); // remove value from stack

// use value...

}

What are the main features of OOP in c plus plus?

The main features of OOP are the same regardless of the language. They are: encapsulation; data hiding; inheritance; and polymorphism.

What is the signature of a function in c plus plus?

A function's signature is defined by the number and type of parameters. Functions with the same signature cannot differ by return type alone. Use of the const keyword also constitutes part of the signature.

What is the need for oops paradigm?

Object oriented programming is a concept that was created because of the need to overcome the problems that were found with using structured programming techniques. While structured programming uses an approach which is top down, OOP uses an approach which is bottom up. Traditionally, programming has placed an emphasis on logic and actions.

Object oriented programming has taken a completely different direction, and will place an emphasis on objects and information. With object oriented programming, a problem will be broken down into a number of units. These units are called objects. The foundation of OOP is the fact that it will place an emphasis on objects and classes.

Objects will be defined, and they will interact inside the system in a number of different ways. There are a number of advantages to be found with using the OOP paradigm, and some of these are simple maintenance, an advanced analysis of complicated programs, and reusability. There are a number of programming languages that use OOP, and some of these are Java, C++, and Ada. One concept that you will want to become familiar with is data modeling. Before you can construct an object oriented system, you will first need to find the objects within the system and determine the relationships they have. This process is called data modeling. There are some other OOP terms that you will want to know.

A class is a unit that holds data and functions which will carry out operations on the data. A class will be comprised of three access modifiers. These three modifiers are protected, private, and public. A member that is public can be accessed and inherited. A member that is designated as private cannot be accessed by objects that exist outside the system. In addition to this, it cannot be inherited. While a member who is protected can be inherited, they cannot be accessed by objects which reside outside of the class hierarchy. Another term that you will hear about often in OOP is objects.

An object is a state of class. It can receive and send messages to other objects, and it can handle data. The objects which exist within software are often based off real world objects, and will behave in the same manner. There are two things that are found with all objects that exist in the real world. These two things are behaviors and states. While behaviors and states are found in real world objects, they can also be found in software objects as well. Another OOP concept that you will need to know is a method. A method is a process that is used to handle an object. A method can be public, protected, or private. The visibility of the member will determine how much of it can be seen by outside objects.

Inheritance is an aspect of OOP that allows subclasses to inherit the traits and characteristics of its superclass. The subclass will inherit all members except those that designated as being private. The subclass may have a large number classes from multiple bases, and this concept is called Multiple Inheritance. It is possible for a subclass to use the behavior of the members it has inherited, and it can also add new members as well. There are two powerful advantages that inheritance has, and these are the implementation of abstract data and reusability.

Encapsulation is another important concept that you will need to know. In a nutshell, encapsulation is responsible for shielding the data within a class from outside objects. It will only reveal the functional information. However, the implementation will be hidden. Encapsulation is a concept which promotes modularity, and it is also crucial for hiding information.

When to use inheritance in c plus plus?

You use inheritance whenever you need a more specialised version of an existing class (the base class). Rather than creating a new class entirely from scratch, and therefore duplicating tried and tested code, you simply build upon the existing class, overriding the existing methods and adding more specialised methods, whilst retaining all the generic functionality of the base class.

How does member function of class define?

Static member functions (or static member methods) are local to the class in which they are declared but, unlike non-static member functions, they are not attached to any instance of the class. That is, they have no access to an implicit this pointer.

Static member functions are often used to declare global functions in conjunction with private static member variables. The variables are not global as they are only accessible to the class itself, but because they are static they exist for the lifetime of the application.

The best possible example of a static member function relates to singleton classes. A singleton class is typically a global class for which one instance (and one instance only) must be guaranteed to remain in scope for the entire duration of the program. A typical usage for such a class might be to enable logging (writing a log of all program activity), and we'd only need one logger.

This means we must actively prevent new instances from being created once the first instance is created, and must ensure it cannot be destroyed while the program is active, intentionally or otherwise. In order to achieve this, the default constructor, the copy constructor and the assignment operator must be declared private with no implementation. This then means that only the class itself can instantiate the one and only instance of the class, and the only way to achieve that is with a static member function and a static member variable.

The following demonstrates the skeleton of a singleton declaration. In a real-life singleton, you would design the remainder of the class just as you would an ordinary class, with instance variables and methods that permit it to carry out its role (whether as a logger or as some other global class for which only one instance is ever required). The example includes simple code to demonstrate its usage as a container for an int using dynamic memory.

Note how the static variable Singleton::instance is initialised to NULL outside of the class declaration (at file scope). This ensures correct initialisation at compile time. This line is typically placed in the class cpp file (implementation file), while the class declaration itself is placed in the class hpp file (header). The one and only instance of the Singleton class is created upon the first call to Singleton::Instance(), which returns a reference to the instance thus permitting access to the instance members.

Since the instance is static, it is guaranteed to remain in scope for the entire life-cycle of the program. It doesn't matter that the static Singleton::instance variable is instantiated dynamically but is never actually released. Since it is a static variable, the memory it points to will be released automatically when the program terminates. The same can also be said of the Singleton::instance->pointer member variable, but it's always good practice to release all non-static members in the private destructor.

The design is such that it would be impossible to inadvertently create two or more instances of the Singleton class, and impossible to destroy the one and only instance until the program terminates.

While there are many other examples of static member functions, the majority merely demonstrate usage that could be far better implemented as a non-static member function or even a friend function. Demonstrations of any practical merit are few and far between (although they do exist), but the Singleton usage is by far the most ingenious and practical usage you will encounter. Microsoft may not agree (a Microsoft singleton isn't strictly a singleton), but the framework shown below is tried and tested, is robust, and does exactly what it says on the tin!

#include

using namespace std;

class Singleton{

private:

Singleton():pointer(new int(100)){} // No creation outside the class.

Singleton(Singleton const&){} // No copying outside the class.

Singleton& operator=(Singleton const&){} // No assignment outside the class.

~Singleton(){delete(pointer);} // No destruction outside the class.

static Singleton* instance; // The only instance there can ever be.

int * pointer; // Dynamic memory allocation (for illustrative purpose).

public:

// Static member function:

static Singleton& Instance(){

if( !instance ) // Creates the instance on first usage only.

instance = new Singleton();

VERIFY(instance != NULL); // Not essential, but prudent.

return(*instance);

}

// A member function (for illustrative purposes).

void foo(void){

cout<<"Singleton::instance resides at memory address 0x"<

cout<<"Singleton::instance->pointer resides at memory address 0x"<

}

// A member accessor and mutator (for illustrative purposes).

int GetValue(void){return(*pointer);}

void SetValue(const int value){*pointer=value;}

};

// Static member initialisation (occurs at compile time). Not optional!

Singleton* Singleton::instance = NULL;

int main(void)

{

// Call singleton methods:

Singleton::Instance().foo(); // The one and only instance is instantiated at this point, just prior to calling foo().

Singleton::Instance().SetValue(3); // Mutate the member variable.

Singleton::Instance().foo(); // Call foo() again.

Singleton::Instance().SetValue(15); // Mutate the member variable.

// Call the member variable accessor:

cout<<"Singleton variable: "<

// It is not possible to delete the instance by accident (the destructor is inaccessible outside of the class):

//delete(&Singleton::Instance()); // Causes compiler error C2248! (MSVC++).

return( 0 );

}

What are virtual constructors or destructors?

If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object. There is a simple solution to this problem

How do you insert a node using doubly linked list in c plus plus?

#include<iostream>

#include<list>

void print_list (std::list<int>& list)

{

for (std::list<int>::const_iterator it=list.begin(); it!=list.end(); ++it)

std::cout << *it << ", ";

std::cout << "\b\b \n";

}

int main()

{

// instantiate a list

std::list<int> list;

// push a new value onto the back of the list:

list.push_back (1);

print_list (list);

// push a new value onto the front of the list:

list.push_front (2);

print_list (list);

// insert a new value at the back of the list

list.insert (list.end(), 3);

print_list (list);

// insert a new value at the front of the list

list.insert (list.begin(), 4);

print_list (list);

// locate value 1.

std::list<int>::const_iterator it=list.begin();

while (it!=list.end() && *it != 1)

++it;

// insert a new value in front of value 1.

list.insert (it, 5);

print_list (list);

}

Output:

1

2, 1

2, 1, 3

4, 2, 1, 3

4, 2, 5, 1, 3

Which is easier 'C' or 'C plus plus'?

Opinion 1:

I think both are easy to use an manipulate although i have never written a c++ program other than hello world but to know c++ you have to know c and c is a standard high level language which is easy to grasp

Opinion 2:

C++ is easier in the end because it is a revised version of the old c language. It is not required to learn C first before learning C++ because you pick up bad habits and when you move to C++, those habits will be hard to get rid of. C++ is a lot more powerful and accurate, it is harder at first but with time it will be a lot easier and more organized than c.

In conclusion, C is easier to learn but not recommended to learn.

I highly recommend people to go straight to C++ to pick up only good habits, then go back to C if you're curious how it works.

Write a program in c to print a mark sheet?

import java.util.*;

import java.lang.String;

import java.io.*;

import java.util.Date;

import java.util.Timer;

class project

{

public static void main(String args[]) throws IOException

{

String sub1,sub2,sub3,sub4,sub5,sub6;

String name,sem;

int m1,m2,m3,m4,m5,m6,m7;

//Date dt = new Date(now.getTime()

int prn_no,seat_no,total;

float per;

float temp;

String msg="*";

long currentTimeInMillis = System.currentTimeMillis();

Date today = new Date( currentTimeInMillis );

Scanner in=new Scanner(System.in);

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter name of student=");

name=b.readLine();

System.out.println("Enter prn number =");

prn_no=in.nextInt();

System.out.println("Enter name of semester=");

sem=b.readLine();

System.out.println("Enter Roll number =");

seat_no=in.nextInt();

System.out.println("Enter first subject name =");

sub1=b.readLine();

System.out.println("Enter marks =");

m1=in.nextInt();

System.out.println("Enter second subject name =");

sub2=b.readLine();

System.out.println("Enter marks =");

m2=in.nextInt();

System.out.println("Enter third subject name =");

sub3=b.readLine();

System.out.println("Enter marks =");

m3=in.nextInt();

System.out.println("Enter fourth subject name =");

sub4=b.readLine();

System.out.println("Enter marks =");

m4=in.nextInt();

System.out.println("Enter fifth subject name =");

sub5=b.readLine();

System.out.println("Enter marks =");

m5=in.nextInt();

System.out.println("\t\t\t\t\t\t DR.BABASAHEB AMBEDKAR MARATHWADA UNIVERSITY");

System.out.println("\t\t\t\t\t\t\tAurangabad-431004");

System.out.println("STUDENT NAME:"+name+"\t\t\tprn :"+prn_no+"\t\t\tSEAT NO:"+seat_no+"\t\t\tSEMESTER:"+sem);

System.out.println("------------------------------------------------------------------------------------");

System.out.println("\n\n| SUBJECTS"+"\t\t\t\t|\tMAXIMUM MARKS"+"\t|\t min marks"+"\t|\tOBTAINED MARKS");

System.out.println("------------------------------------------------------------------------------------");

if(m1>40)

msg="";

else

msg="*";

System.out.println("|"+sub1+"\t\t\t\t\t\t|\t100\t\t\t\t|\t40\t\t\t|\t"+m1);

if(m2>40)

msg="";

else

msg="*";

System.out.println("|"+sub2+"\t\t\t\t\t\t|\t100\t\t\t\t|\t40\t\t\t|\t"+m2);

//System.out.println(+sub2+"\t\t\t"+"|"+"\t\t100"+"\t\t\t"+"|"+"\t\t40"+"\t\t\t\t"+"|"+"\t\t"m2+msg+"\t|");

if(m3>40)

msg="";

else

msg="*";

System.out.println("|"+sub3+"\t\t\t\t\t\t|\t100\t\t\t\t|\t40\t\t\t|\t"+m3);

//System.out.println(+sub3+"\t\t\t"+"|"+"\t\t100"+"\t\t\t"+"|"+"\t\t40"+"\t\t\t\t"+"|"+"\t\t"m3+msg+"\t|");

if(m4>40)

msg="";

else

msg="*";

System.out.println("|"+sub4+"\t\t\t\t\t\t|\t100\t\t\t\t|\t40\t\t\t|\t"+m4);

//System.out.println(+sub4+"\t\t\t"+"|"+"\t\t100"+"\t\t\t"+"|"+"\t\t40"+"\t\t\t\t"+"|"+"\t\t"m4+msg+"\t|");

if(m5>40)

msg="";

else

msg="*";

System.out.println("|"+sub5+"\t\t\t\t\t\t|\t100\t\t\t\t|\t40\t\t\t|\t"+m5);

//System.out.println(+sub5+"\t\t\t"+"|"+"\t\t100"+"\t\t\t"+"|"+"\t\t40"+"\t\t\t\t"+"|"+"\t\t"m5+msg+"\t|");

System.out.println("------------------------------------------------------------------------------------");

total=m1+m2+m3+m4+m5;

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t TOTAL ::"+total+"/500");

temp=(float)total/500;

per=temp*100;

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t PERCENTAGE ::"+per+"%");

System.out.println("------------------------------------------------------------------------------------");

if(m1<40&&m2<40&&m3<40&&m4<40&&m5<40)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT ::DROPPED");

System.out.println("------------------------------------------------------------------------------------");

}

else if(m1<40&&m2<40m3<40&&m4<40&&m5<40)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT ::A.T.K.T.");

}

else if(per<35)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT ::FAILED");

}

else if(per>=35&&per<40)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT ::passed");

}

else if(per>=40&&per<59)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT :::passed with SECOND CLASS");

}

else if(per>=60&&per<75)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT :passed with first class");

}

else if(per>=75)

{

System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t"+"|"+"\t\t RESULT :passed with DISTINCTION class");

}

System.out.println( today );

}

}

How do you put a c plus plus program on a website?

If you mean how do you upload the C++ source code to a website, the simplest way is to organise your solution within a parent folder, with sub-folders for each project in the solution, and ZIP the parent folder. You can then upload the ZIP file just as you would any other file.

If you mean how do you upload the source code so that it may be viewed and read in a browser, you will have to copy/paste the code into an HTML file using appropriate tags to format the code. Websites that expect you to upload source code will normally provide you with the tools to do so, usually just by wrapping the code in HTML <code></code> tags. If your code is modularised (multiple source files and headers), you should wrap each file separately and annotate the text to indicate which file is which (or just place the file name as a comment in the source itself, along with any required copyrights). If you're uploading to your own website, then it would be worth looking for a tool that automatically converts your source code into the required HTML.

Static variable in c plus plus?

There are two uses for a static variable in C++. When declared outside of a class, a variable is regarded as being global. However a static variable is deemed local to the file in which it is declared. That is, the variable is scoped to the file, and cannot be accessed by code outside of that file. This aspect was inherited from C.

C++ also allows static variables to be declared inside a class. In this case, the variable is local to the class. By contrast, instance variables (non-static member variables) are local to each instance of the class. With static variables, there is only one instance of each variable which can be shared by all instances of the class. It is not unlike a global but it is scoped to the class.

Since all static variables are instantiated at compile time, they exist for the entire duration a program runs. Even if they fall from scope, they never lose their value. Static variables defined within a class are also available even when no instances of the class are instantiated. Their visibility outside of the class is dependent upon whether they are declared public, protected or private.

What is difference constructor and function in programming C plus plus?

A Constructor is called when you are making a new instance of a class and member functions are functions that you can call within your class or else call using the instance of that class.

for example


class Foo {


public:

int bar;

Foo(int bar) {this->bar = bar;}

inc_bar(); {this->bar++;}

};


Foo instance(10); // Constructor is called and bar is set to 10

cout << instance.bar << endl;

instance.inc_bar(); // call the member function to increment bar

cout << instance.bar << endl;

Is there anything similar between C and C plus plus with reference to data hiding?

No. Data hiding is a feature of object oriented programming. C does not support OOP, and therefore has no private member access. All members are public in C.

A program for queue ADT by using arrays in c plus plus?

Arrays are not suitable for implementing queues because while they are ideal for adding to the end, the are not ideal for extraction from the beginning. For that you need a deque. Regardless, the STL (standard template library) already provides an efficient queue ADT in std::queue.